I was trying to make a Queue<Action>
. When I went to dequeue and invoke each action, it kept stopping at 4
. I walked through the code and it was processing everything correctly. What am I doing wrong here?
public class Program
{
static void Main(string[] args)
{
SomeClass test = new SomeClass();
test.EnqueuePrint("1");
test.EnqueuePrint("2");
test.EnqueuePrint("3");
test.EnqueuePrint("4");
test.EnqueuePrint("5");
test.EnqueuePrint("6");
test.EnqueuePrint("7");
test.EnqueuePrint("8");
Console.WriteLine("Process the queue!");
test.ProcessQueue();
}
}
public class SomeClass
{
private Queue<Action> _actionQueue;
public SomeClass()
{
_actionQueue = new Queue<Action>();
}
public void EnqueuePrint(string message)
{
_actionQueue.Enqueue(() => Print(message));
}
private void Print(string message)
{
Console.WriteLine(message);
}
public void ProcessQueue()
{
for (int i = 0; i < _actionQueue.Count; i++)
{
_actionQueue.Dequeue().Invoke();
}
}
}
Output
Process the queue!
1
2
3
4
The problem is that the count decreases as you dequeue items. So by the time i
is 4, the count is also 4, so the loop stops.
If you want to keep dequeuing until the queue is empty, you could use:
while (_actionQueue.Count > 0)
{
_actionQueue.Dequeue().Invoke();
}
Or if the action might (in other cases) add more items to the queue and you only want to process as many items as there were originally, you could use:
int originalCount = _actionQueue.Dequeue();
for (int i = 0; i < originalCount; i++)
{
_actionQueue.Dequeue().Invoke();
}
See more on this question at Stackoverflow