Collection was modified; enumeration operation may not execute

For quite some time I have been seeing the following error in event logs of our web server.

Exception information: 
    Exception type: InvalidOperationException 
    Exception message: Collection was modified; enumeration operation may not execute.
   at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
   at System.Collections.Generic.List`1.Enumerator.MoveNextRare()
   at System.Collections.Generic.List`1.Enumerator.MoveNext()

I am totally aware of what this error means what is cause of the error. Basically it comes down to that if you are using foreach loop through your collection, you can not change that collection object while this loop has not completed. The thing that was puzzling me was that as far as i knew there was no code path that was adding or removing any thing from that collection at all while the code throwing the exception was executing. Lately this error was getting thrown more often than ever. When I started to connect dots, one thing that was kind of contradicting was that as the web site was showing more and more traffic, the frequency of the error was going up as well. For a moment I thought that if more users are running into this error then traffic should decrease. That's when it kind of hit me that there is something in the work flow that may be triggering some change in the collection.

When followed the code path of the page rendering, I found one place that was changing a property of object in the collection and then triggered a sort on the collection. Well, there it was. Although entries were not being added or deleted from collection but they were certainly getting sorted while other piece of the code that was accessing that collection was iterating over it. In my case that sort was not required, so I removed that sorting work flow and I never saw the exception again. And traffic on the site actually increased as well because now more users were able to access the pages.

So if you are having similar issues here are some steps that you can take to diagnose and fix this issue.

  • Look at the code to see where objects are getting added or deleted from that collection. If this is a static object, then you will have to find a way to synchronize the access to it.

  • Look for code that may be modifying the collection in any way, sorting etc. Again proect the access if object is static.

  • If you can not avoid modifications, then clone the collection before iterating over it. One of the way to do it will be to call ToList extension method on your collection to make a copy of it.

Hope this helps you guys in dealing with this exception that can be some time subtle to diagnose.

comments powered by Disqus




7.3 °C / 45.2 °F

weather conditions Clouds

Monthly Posts

Blog Tags