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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With