Strange “Collection was modified after the enumerator was instantiated” exception

自古美人都是妖i 提交于 2019-11-30 17:44:01

I suspect the place to start looking will be at any places where you manipulate the list - i.e. insert/remove/re-assign items. My suspicion is that there will be a callback/even-handler somewhere that is getting fired asynchronously (perhaps as part of the XNA paint etc loops), and which is editing the list - essentially causing this problem as a race condition.

To check if this is the case, put some debug/trace output around the places that manipulate the list, and see if it ever (and in particular, just before the exception) runs the manipulation code at the same time as your console output:

private void SomeCallback()
{
   Console.WriteLine("---Adding foo"); // temp investigation code; remove
   components.AddLast(foo);
   Console.WriteLine("---Added foo"); // temp investigation code; remove
}

Unfortunately, such things are often a pain to debug, as changing the code to investigate it often changes the problem (a Heisenbug).

One answer would be to synchronize access; i.e. in all the places that edit the list, use a lock around the complete operation:

LinkedList<Component> components = new LinkedList<Component>();
readonly object syncLock = new object();
...
private void PrintComponentList()
{
    lock(syncLock)
    { // take lock before first use (.Count), covering the foreach
        Console.WriteLine("---Component List: " + components.Count
              + " entries---");
        foreach (Component c in components)
        {
           Console.WriteLine(c);
        }
        Console.WriteLine("------");
    } // release lock
}

and in your callback (or whatever)

private void SomeCallback()
{
   lock(syncLock)
   {
       components.AddLast(foo);
   }
}

In particular, a "complete operation" might include:

  • check the count and foreach/for
  • check for existance and insert/remove
  • etc

(i.e. not the individual/discrete operations - but units of work)

arash

Instead of foreach, I use while( collection.count >0) then use collection[i].

I don't know if this is relevant to the OP but I had the same error and found this thread during a google search. I was able to solve it by adding a break after removing an element in the loop.

foreach( Weapon activeWeapon in activeWeapons ){

            if (activeWeapon.position.Z < activeWeapon.range)
            {
                activeWeapons.Remove(activeWeapon);
                break; // Fixes error
            }
            else
            {
                activeWeapon.position += activeWeapon.velocity;
            }
        }
    }

If you leave out the break, you will get the error "InvalidOperationException: Collection was modified after the enumerator was instantiated."

Saikat Chakraborty

Using Break could be a way but it may impact your series of operation. What I do in that case in simply convert the foreach to traditional for loop

for(i=0; i < List.count; i++)
{
    List.Remove();
    i--;
}

This works without any issues.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!