How to make ObservableCollection thread-safe?

前端 未结 4 854
天命终不由人
天命终不由人 2020-11-29 03:42
System.InvalidOperationException: Collection was modified; enumeration operation may not execute.

I am adding/removing from an ObservableCollection

4条回答
  •  时光说笑
    2020-11-29 04:15

    As of .net framwork 4.5 you can use native collection synchronization.

    BindingOperations.EnableCollectionSynchronization(YourCollection, YourLockObject);

    YourLockObject is instance of any object e.g. new Object();. Use one per collection.

    This eliminates the need of some special class or anything. Just enable and enjoy ;)

    [edit] As stated in the comments by Mark and Ed (thanks for clarifying!), this does not relieve you from locking the collection on updates as it just synchonizes the collection-view-binding and does not magically make the collection thread-safe itself. [/edit]

    PS: BindingOperations resides in Namespace System.Windows.Data.

提交回复
热议问题