Queue ForEach loop throwing InvalidOperationException

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


This is typical behavior of enumerators. Most enumerators are designed to function correctly only if the underlying collection remains static. If the collection is changed while enumerating a collection then the next call to MoveNext, which is injected for you by the foreach block, will generate this exception.

The Dequeue operation obviously changes the collection and that is what is causing the problem. The workaround is to add each item you want removed from the target collection into a second collection. After the loop is complete you can then cycle through the second collection and remove from the target.

However, this might be a bit awkward, at the very least, since the Dequeue operation only removes the next item. You may have to switch to a different collection type which allows arbitrary removals.

If you want to stick with a Queue then you will be forced to dequeue each item and conditionally re-queue those items which should not be removed. You will still need the second collection to keep track of the items that are okay to omit from the re-queueing.


Old post but thought I would provide a better answer:

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


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

As DarkUrse's original answer used a do/while and that would cause an exception if the queue is empty when trying to de-queue on the empty queue, also added a protection against a null queue


You are modifying queue inside of foreach loop. This is what causes the exception.
Simplified code to demonstrate the issue:

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

foreach (var i in queue)
{
    queue.Dequeue();
}

Possible solution is to add ToList(), like this:

foreach (var i in queue.ToList())
{
    queue.Dequeue();
}