I have a synchronized hash table from which I regularly delete some entries. This code executes multiple threads. Therefore, I block the entire foreach, but sometimes I get InvalidOperationException: Collection has been changed ... in Hashtable.HashtableEnumerator.MoveNext () - that is, in the foreach loop. What am I doing wrong? Is blocking enough?
private static readonly Hashtable sessionsTimeoutData = Hashtable.Synchronized(new Hashtable(5000));
private static void ClearTimedoutSessions() { List keysToRemove = new List(); long now = DateTime.Now.Ticks; lock (sessionsTimeoutData) { TimeoutData timeoutData; foreach (DictionaryEntry entry in sessionsTimeoutData) { timeoutData = (TimeoutData)entry.Value; if (now - timeoutData.LastAccessTime > timeoutData.UserTimeoutTicks) keysToRemove.Add((ulong)entry.Key); } } foreach (ulong key in keysToRemove) sessionsTimeoutData.Remove(key); }
reticent
source share