<p>I need to enumerate though generic IList&lt;> 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."</p>

<p>What is a good way of doing threadsafe foreach on a IList&lt;>? prefferably without cloning the entire list. It is not possible to clone the actual objects referenced by the list.</p>

[{'answer_id': 66638, 'author': 'Patrick', 'author_id': 429, 'author_profile': 'https://Stackoverflow.com/users/429', 'pm_score': 1, 'selected': False, 'text': "<p>Forech depends on the fact that the collection will not change. If you want to iterate over a collection that can change, use the normal for construct and be prepared to nondeterministic behavior. Locking might be a better idea, depending on what you're doing.</p>\n"}, {'answer_id': 66653, 'author': 'Jason Punyon', 'author_id': 6212, 'author_profile': 'https://Stackoverflow.com/users/6212', 'pm_score': 2, 'selected': False, 'text': '<p>There is no such operation.  The best you can do is </p>\n\n<pre>\n<code>\nlock(collection){\n    foreach (object o in collection){\n       ...\n    }\n}\n</code></pre>\n'}, {'answer_id': 66655, 'author': 'John Millikin', 'author_id': 3560, 'author_profile': 'https://Stackoverflow.com/users/3560', 'pm_score': 5, 'selected': True, 'text': "<p>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.</p>\n"}, {'answer_id': 66661, 'author': 'jamuraa', 'author_id': 9805, 'author_profile': 'https://Stackoverflow.com/users/9805', 'pm_score': 0, 'selected': False, 'text': '<p>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). </p>\n'}, {'answer_id': 66680, 'author': 'jan.vdbergh', 'author_id': 9540, 'author_profile': 'https://Stackoverflow.com/users/9540', 'pm_score': 2, 'selected': False, 'text': "<p>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.</p>\n\n<p>A few possibilities come to mind:</p>\n\n<ul>\n<li>Clone the list. Now each enumerator has its own copy to work on.</li>\n<li>Serialize the access to the list. Use a lock to make sure no other thread can modify it while it is being enumerated. </li>\n</ul>\n\n<p>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.</p>\n"}, {'answer_id': 66689, 'author': 'Forgotten Semicolon', 'author_id': 1960, 'author_profile': 'https://Stackoverflow.com/users/1960', 'pm_score': 2, 'selected': False, 'text': '<pre><code>ICollection MyCollection;\n// Instantiate and populate the collection\nlock(MyCollection.SyncRoot) {\n  // Some operation on the collection, which is now thread safe.\n}\n</code></pre>\n\n<p>From <a href="http://msdn.microsoft.com/en-us/library/system.collections.icollection.syncroot.aspx" rel="nofollow noreferrer">MSDN</a></p>\n'}, {'answer_id': 66758, 'author': 'Jorge Córdoba', 'author_id': 2695, 'author_profile': 'https://Stackoverflow.com/users/2695', 'pm_score': 2, 'selected': False, 'text': '<p>You\'ll find that\'s a very interesting topic.</p>\n\n<p>The best approach relies on the ReadWriteResourceLock which use to have big performance issues due to the so called Convoy Problem.</p>\n\n<p>The best article I\'ve found treating the subject is <a href="http://msdn.microsoft.com/en-us/magazine/cc163599.aspx" rel="nofollow noreferrer">this one</a> by Jeffrey Richter which exposes its own method for a high performance solution.</p>\n'}, {'answer_id': 68652, 'author': 'Jeffrey L Whitledge', 'author_id': 10174, 'author_profile': 'https://Stackoverflow.com/users/10174', 'pm_score': 2, 'selected': False, 'text': "<p>So the requirements are: you need to enumerate through an IList&lt;> without making a copy while simultaniously adding and removing elements.</p>\n\n<p>Could you clarify a few things? Are insertions and deletions happening only at the beginning or end of the list?\nIf modifications can occur at any point in the list, how should the enumeration behave when elements are removed or added near or on the location of the enumeration's current element?</p>\n\n<p>This is certainly doable by creating a custom IEnumerable object with perhaps an integer index, but only if you can control all access to your IList&lt;> object (for locking and maintaining the state of your enumeration). But multithreaded programming is a tricky business under the best of circumstances, and this is a complex probablem.</p>\n"}, {'answer_id': 1089169, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': "<p>Default behavior for a simple indexed data structure like a linked list, b-tree, or hash table is to enumerate in order from the first to the last.  It would not cause a problem to insert an element in the data structure after the iterator had already past that point or to insert one that the iterator would enumerate once it had arrived, and such an event could be detected by the application and handled if the application required it.  To detect a change in the collection and throw an error during enumeration I could only imagine was someone's (bad) idea of doing what they thought the programmer would want.  Indeed, Microsoft has fixed their collections to work correctly.  They have called their shiny new unbroken collections ConcurrentCollections (System.Collections.Concurrent) in .NET 4.0.  </p>\n"}, {'answer_id': 54828413, 'author': 'folmerbrem', 'author_id': 3046475, 'author_profile': 'https://Stackoverflow.com/users/3046475', 'pm_score': 1, 'selected': False, 'text': '<p>I recently spend some time multip-threading a large application and had a lot of issues with the foreach operating on list of objects shared across threads.</p>\n\n<p>In many cases you can use the good old for-loop and immediately assign the object to a copy to use inside the loop. Just keep in mind that all threads writing to the objects of your list should write to different data of the objects. Otherwise, use a lock or a copy as the other contributors suggest.</p>\n\n<p>Example:</p>\n\n<pre><code>foreach(var p in Points)\n{\n    // work with p...\n}\n</code></pre>\n\n<p>Can be replaced by:</p>\n\n<pre><code>for(int i = 0; i &lt; Points.Count; i ++)\n{\n   Point p = Points[i];\n   // work with p...\n}\n</code></pre>\n'}, {'answer_id': 62415436, 'author': 'Snapperhead', 'author_id': 3150313, 'author_profile': 'https://Stackoverflow.com/users/3150313', 'pm_score': 0, 'selected': False, 'text': '<p>This is something that I\'ve recently had to deal with and to me it really depends on what you\'re doing with the list.  </p>\n\n<p>If you need to use the list at a point in time (given the number of elements currently in it) AND another thread can only ADD to the end of the list, then maybe you just switch out to a FOR loop with a counter.  At the point you grab the counter, you\'re only seeing X numbers of elements in the list.  You can walk through the list (while others are adding to the end of it) . . . should not cause a problem.  </p>\n\n<p>Now, if the list needs to have items taken OUT of it by other threads, or CLEARED by other threads, then you\'ll need to implement one of the locking mechanisms mentioned above.  Also, you may want to look at some of the newer "concurrent" collection classes (though I don\'t believe they implement IList - so you may need refactor for a dictionary).</p>\n'}]
['https://Stackoverflow.com/questions/66622', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3263/']