I am now using Visual Studio 2010, which comes with a nice code analysis tool.
Is there a way to instruct it to locate calls which try to modify the collection while it is being iterated? And can any other code analysis do?
The objective is preventing exceptions such as the one in the title occurring at runtime.
This is normally a bug induced by threading, not properly locking access to a collection that’s shared between threads. Especially easy to overlook in code that iterates the collection because that in itself is a thread-safe operation. Adding or removing elements while it is being iterated is what causes the kaboom. And yes, hard to diagnose because it doesn’t happen on the code that modified the collection. You only find out long after the damage was done.
Also possible in non-threaded code but that’s easy to debug.
Static analyzers that can analyze timing problems in code do not exist. Execution timing is entirely non-deterministic. If they did, writing thread-safe code would be a heckofalot easier. Anybody that solves this problem while at the same time not completely destroying the efficiency is going to get a Nobel.