I've got a good old InvalidOperationException
being thrown with the standard message
Collection was modified; enumeration operation may not execute.
The problem is, the enumerator isn't modifying itself, for example:
private TRoute _copyRoute(TRoute route)
{
TRoute tempRoute = new TRoute();
tempRoute.Initialize(route.Resource);
foreach (TVisit visit in route)
{
tempRoute.Add(visit);
}
tempRoute.EndLocation = route.EndLocation;
return tempRoute;
}
My code is multi-threaded (circa 12-15 threads for this example) and each thread is supposed to be working on its own deep clone of a route. Obviously something is going wrong somewhere, but, my question is how do I track this down with so many threads? Reducing the number significantly stops the problem manifesting itself.
In this case my route instance is an IList so I can play around with adding things to the interface. Underneath it has it's own List implementation.
EDIT
Just to add, I could ToArray() or ToList() this and maybe ignore the problem here but I don't really want to do that, I want to locate the cause. For example:
If I change it to the following:
private TRoute _copyRoute(TRoute route)
{
TRoute tempRoute = new TRoute();
tempRoute.Initialize(route.Resource);
foreach (TVisit visit in route.ToList())
{
tempRoute.Add(visit);
}
tempRoute.EndLocation = route.EndLocation;
return tempRoute;
}
Then I fail on this Assert, because a chance has occurred just before ToList()... I need to try and find out where that change is occuring
TRoute tempRoute1 = CopyRoute(route1);
TRoute tempRoute2 = CopyRoute(route2);
Debug.Assert(tempRoute1.Count == route1.Count);