Update item in ObservableCollection as Thread safe

点点圈 提交于 2021-02-08 12:15:29

问题


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

Here is my way.

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.

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

Is there any better way ?

  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/26d9d070619de58fa8e28ea21fff04fd

Edit (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..


回答1:


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.

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



来源:https://stackoverflow.com/questions/53097349/update-item-in-observablecollection-as-thread-safe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!