Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Threadsafe foreach enumeration of lists

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.

like image 640
Radu094 Avatar asked Sep 15 '08 20:09

Radu094


People also ask

Is enumeration through a collection a thread safe procedure?

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.

How can I make the enumerator thread-safe?

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!

How do you make a thread safe list in C?

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.

What is thread safe collection in net?

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.


2 Answers

ICollection MyCollection;
// Instantiate and populate the collection
lock(MyCollection.SyncRoot) {
  // Some operation on the collection, which is now thread safe.
}

From MSDN

like image 59
Forgotten Semicolon Avatar answered Oct 16 '22 02:10

Forgotten Semicolon


There is no such operation. The best you can do is


lock(collection){
    foreach (object o in collection){
       ...
    }
}
like image 39
Jason Punyon Avatar answered Oct 16 '22 02:10

Jason Punyon