Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enumeration collection was modified resistant

Tags:

c#

Is there a wrapper that completely removes this error? I have multiple loops on multiple threads and it is impossible for me to predict whether a collection is going to get modified in the middle of the foreach, I imagine it could be easily achievable by catching this specific error and getting a new handler for the collection and looping through the remaining elements however I am not advanced enough to override the default behavior with such a function.

like image 942
user2534406 Avatar asked Feb 16 '23 01:02

user2534406


1 Answers

Assuming you're using .NET 4, you could use one of the collections in System.Collections.Concurrent, such as ConcurrentBag. However, you haven't really specified any requirements, so it's hard to know whether ConcurrentBag itself would meet them.

If you read the thread safety documentation for most collections, you'll find that they don't support safe modification from one thread while the collection is being read (or modified) by another, without locking. It's fine to read from a List<T> etc from multiple threads if it's not being modified by anything, but you shouldn't have even a single thread modifying it.

Ideally, try to design your code so that you don't require this unfettered write access to shared collections - but if you really need it, use a type which was designed for it.

like image 63
Jon Skeet Avatar answered Feb 23 '23 04:02

Jon Skeet