I need to enumerate though generic IList<> of objects. The contents of the list may change, as in being added or removed by other threads, and this will kill my enumeration with a "Collection was modified; enumeration operation may not execute."
What is a good way of doing threadsafe foreach on a IList<>? prefferably without cloning the entire list. It is not possible to clone the actual objects referenced by the list.
As MSDN correctly states, "enumerating through a collection is intrinsically not a thread-safe procedure". Even if you use a synchronized collection (or one of the concurrent collections in .NET 4.0), and all methods use a lock statement internally, iteration using foreach may still fail.
Another possible upgrade to the thread-safe enumerator is using ReaderWriterLock (or even better, ReaderWriterLockSlim) in place of Monitor. As iterations do not change the collection, it makes sense to allow many concurrent iterations at once, and only block concurrent changes to the collection. This is what ReaderWriterLock is for!
Thread Safe List With the ConcurrentQueue Class in C The ConcurrentQueue class is used to create a thread-safe queue data structure in C#. The ConcurrentQueue works on the principle of first in, first out, just like the List in C#. The ConcurrentQueue object can be used instead of the List object to create a thread-safe data structure.
Thread-Safe Collections. The .NET Framework 4 introduces the System.Collections.Concurrent namespace, which includes several collection classes that are both thread-safe and scalable. Multiple threads can safely and efficiently add or remove items from these collections, without requiring additional synchronization in user code.
ICollection MyCollection;
// Instantiate and populate the collection
lock(MyCollection.SyncRoot) {
// Some operation on the collection, which is now thread safe.
}
From MSDN
There is no such operation. The best you can do is
lock(collection){
foreach (object o in collection){
...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With