Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collection was modified; enumeration operation may not execute for hashtable [duplicate]

Tags:

c#

enumeration

I have this timer function, it gives me following exception.
Collection was modified; enumeration operation may not execute once i remove the object from hashtable.

what is the solution to implement similar functionality

void timerFunction(object data)
    {
    lock (tMap.SyncRoot)
    {
      foreach (UInt32 id in tMap.Keys)
      {
         MyObj obj=(MyObj) runScriptMap[id];
         obj.time = obj.time -1;
         if (obj.time <= 0)
         {                      
            tMap.Remove(id);
         }
       }
    }
like image 410
Kazoom Avatar asked Dec 10 '22 17:12

Kazoom


1 Answers

The traditional way is, in your foreach loop, to collect the items to be deleted into, say, a List. Then once the foreach loop has finished, do another foreach over that List (not over tMap this time), calling tMap.Remove:

void timerFunction(object data)
{
  lock (tMap.SyncRoot)
  {
    List<UInt32> toRemove = new List<UInt32>();

    foreach (UInt32 id in tMap.Keys)
    {
      MyObj obj=(MyObj) runScriptMap[id];
      obj.time = obj.time -1;
      if (obj.time <= 0)
      {                      
        toRemove.Add(id);
      }
    }

    foreach (UInt32 id in toRemove)
    {
      tMap.Remove(id);
    }
  }
}
like image 94
itowlson Avatar answered Dec 28 '22 23:12

itowlson