Threadsafe foreach enumeration of lists

Your problem is that an enumeration does not allow the IList to change. This means you have to avoid this while going through the list.

A few possibilities come to mind:

  • Clone the list. Now each enumerator has its own copy to work on.
  • Serialize the access to the list. Use a lock to make sure no other thread can modify it while it is being enumerated.

Alternatively, you could write your own implementation of IList and IEnumerator that allows the kind of parallel access you need. However, I'm afraid this won't be simple.


Cloning the list is the easiest and best way, because it ensures your list won't change out from under you. If the list is simply too large to clone, consider putting a lock around it that must be taken before reading/writing to it.


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


lock(collection){
    foreach (object o in collection){
       ...
    }
}