Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding how a foreach collection gets modified

How do I find out which function or target is modifying the items in a foreach loop in a multithreaded application?

I continously keep getting the error "Collection was modified; enumeration operation may not execute". I'm not removing or adding any items to the generic list within the for loop. I want to find out how it is getting modified. What is the best way to do this?

Thanks

like image 618
Josh Avatar asked Dec 28 '25 11:12

Josh


1 Answers

Wait a minute - I think we've all missed the point.

The collection classes are not thread-safe. If the collection is being accessed by multiple threads without thread-locking, then you need to fix that. It's a particularly insidious problem because it will work correctly [edit - or throw a predictable exception] 99.999% of the time, and 0.001% of the time it will do something totally unpredictable and nearly impossible to reproduce.

A simple approach is to use lock{} statements around EVERY place where ANY code accesses the collection. That may be slight overkill but it is the safest plan. For iteration you can either put a lock around the whole loop or if you don't want to block out other threads that long, just lock it long enough to make a snapshot:

object[] snap;
lock (list)
{
   snap = list.ToArray();
}
foreach (object x in snap) ...
like image 131
JayMcClellan Avatar answered Dec 31 '25 01:12

JayMcClellan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!