将 ObservableCollection 中的项目更新为线程安全 [英] Update item in ObservableCollection as Thread safe

查看:138
本文介绍了将 ObservableCollection 中的项目更新为线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有什么好的方法来更新一个Item在 ObservableCollection 中作为线程安全"?

Is there any good way to update a Item in ObservableCollection as "Thread safe" ?

这是我的方式.

var target = MyCollection.Where(i => i.Key== a_Key).Single();
MyCollection[MyCollection.IndexOf(target)] = NewValue;

但是我担心.如果我使用索引,它可能不是线程安全的..请给我建议.

But I worry. If I use Index, It may not thread safe.. Please advice me.

在互联网上,有一些线程安全的 ObservableCollection.我想用一号.

In internet, THere is some thread-safe-ObservableCollection. I want to use No.1.

有没有更好的方法?

  1. https://gist.github.com/thomaslevesque/10023516
  2. https://www.codeproject.com/Articles/64936/Multithreaded-ObservableImmutableCollection
  3. https://www.nuget.org/packages/ParallelExtensionsExtras/
  4. https://gist.github.com/anonymous/26d9d070619de58fa8e204fd>

编辑 (1)

当我使用索引替换时,我不得不担心其他线程更改或排序集合的可能性.索引可能会更改,直到我覆盖为止.有没有可能?

When I used index to replace, I have to worry the possibility that other thread change or sort Collection. Index maybe change until I overwrite. Is there the possibility ?

我想知道更多更新/覆盖收藏项的好方法.

I want to know more good way to update/Overwrite a Collection item.

如果有一种方法可以在没有索引的情况下更新/覆盖项目,请教我..

If there is a way to update/overwrite a item WITHOUT index, Please teach me..

推荐答案

无论如何,您只能在调度程序线程上更新数据绑定的 ObservableCollection,除非您使用 .NET Framework 4.5 中引入的 BindingOperations.EnableCollectionSynchronization 方法.

You can only update a data-bound ObservableCollection<T> on the dispatcher thread anyway, unless you use the BindingOperations.EnableCollectionSynchronization method that was introduced in .NET Framework 4.5.

这个方法在访问集合时接受一个object来锁定.请参阅 this 一个例子的答案.

This method accepts an object to lock when accessing the collection. Please see this answer for an example.

这篇关于将 ObservableCollection 中的项目更新为线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆