Alex Rivera | Logout

Threadsafe foreach enumeration of lists

Asked 2008-09-15T20:29:54.770
11

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.

Edit
Report

1 Answer

0

Wrap the list in a locking object for reading and writing. You can even iterate with multiple readers at once if you have a suitable lock, that allows multiple concurrent readers but also a single writer (when there are no readers).

answered 2008-09-15T20:33:51.420

Your Answer