我试图制作一个Queue<Action>
. 当我去出队并调用每个动作时,它一直停在4
. 我浏览了代码,它正在正确处理所有内容。我在这里做错了什么?
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();
}
}
}
输出
Process the queue!
1
2
3
4