问题
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 ?
- https://gist.github.com/thomaslevesque/10023516
- https://www.codeproject.com/Articles/64936/Multithreaded-ObservableImmutableCollection
- https://www.nuget.org/packages/ParallelExtensionsExtras/
- 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