Queue ForEach loop throwing InvalidOperationException

keyboardP picture keyboardP · Jun 4, 2011 · Viewed 32.1k times · Source

I haven't used Queues<T> to any real degree before, so I might be missing something obvious. I'm trying to iterate through a Queue<EnemyUserControl> like this (every frame):

foreach (var e in qEnemy)
{
     //enemy AI code
}

When an enemy dies, the enemy user control raises an event I've subscribed to and I do this (the first enemy in the queue is removed by design):

void Enemy_Killed(object sender, EventArgs e)
{      
     qEnemy.Dequeue();

     //Added TrimExcess to check if the error was caused by NULL values in the Queue (it wasn't :))
     qEnemy.TrimExcess();
}

However, after the Dequeue method is called, I get an InvalidOperationException on the foreach loop. When I use Peek instead, there are no errors so it has to do something with the changing of the Queue itself since Dequeue removes the object. My initial guess is that it's complaining that I'm modifying a collection which is being iterated by the Enumerator, but the dequeuing is being performed outside the loop?

Any ideas what could be causing this issue?

Thanks

Answer

DarkUrse picture DarkUrse · Nov 25, 2013

I know this is an old post but what about the following :

var queue = new Queue<int>();
queue.Enqueue(1);
queue.Enqueue(2);

while (queue.Count > 0)
{
  var val = queue.Dequeue();
}

Cheers