You get those "System.InvalidOperationException: Collection was modified;
enumeration operation may not execute." because you're looping through a collection and you've removed/added an object during that iteration aswell.
To solve this, for example at dropping dead connections, keep a System.Collections.Generic.List<sometype> object, and when you are iterating through the collection and an object needs to be removed, you add the index (integer) of that object to the List collection.
Then, when the iteration has finished, you loop through the 'index list', and you remove each object off the collection. That way you aren't 'modifying the collection during enumeration'.
To ensure threadsafety at collections (for example, removing/adding objects to same collection on different thread) you should wrap the collection with the 'lock' keyword during the iteration. That way threads who also are accessing that object will wait till the other one has unlocked the object.
Example:
PHP Code:
Dictionary<int, someClass> myCollection = new Dictionary<int, someClass>();
(...)
PHP Code:
List<int> removeIndexList = new List<int>();
lock(myCollection)
{
foreach(someClass lClass in myCollection.Values)
{
if(stuff etc)
add to removelist collection
}
}
// iterate through removelist collection and remove objects from myCollection
Soz for the bad formatting.
Should help you guys. =]
- Nillus
EDIT:
Avoid deadlocking of threads, don't let object A lock object B etc etc, got to run now so no time for explanation, google it. ;P