Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
887 views
in Technique[技术] by (71.8m points)

c# - How to make ObservableCollection thread-safe?

System.InvalidOperationException: Collection was modified; enumeration operation may not execute.

I am adding/removing from an ObservableCollection which is not on a UI thread.

I have a method names EnqueueReport to add to the colleciton and a DequeueReport to remove from the colleciton.

The flow of steps is as below :-

  1. 1.call EnqueueReport whenever a new report is requested
  2. call a method every few seconds to check if the report is generated (this has a foreach loop that checks the generated status of all reports in ObservableCollection)
  3. call DequeueReport if the report is generated

I am not much in C# libraries. Can someone please guide me on this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...