I am trying to delete all the items in my Hashtable with this code
Monitor.Enter(myhasatable);
foreach (object key in myhasatable.Keys)
{
myhasatable.Remove(key.ToString());
}
Monitor.Exit(myhasatable);
I am getting error :
system.invalidoperationexception collection was modified enumeration
operation may not execute
and them my server get stuck until I refresh it
Any idea what can cause this problem?
Thnaks
You can’t modify a collection while you iterate over it. Try calling
Clearinstead.Also, try to avoid using
Hashtablein new code. Prefer to useDictionary<TKey, TValue>if you have a choice.Your server deadlocks because the
Monitor.Exitis not reached when an exception is thrown on the line before. You could fix this by putting that code in a finally block. But instead of using aMonitor, I suggest you uselockas this automatically releases the lock for you even in the presence of exceptions.With all these changes, your code becomes much simpler: