如何反复迭代并发队列?
How do I iterate concurrent queue repeatedly?
我正在使用 Winforms 并以 .Net 4.5 为目标
我想迭代并发队列,只要它有项目。在我的应用程序中,用户可以随时向并发队列添加和删除项目。
示例代码:
ConcurrentQueue<string> cq = new ConcurrentQueue<string>();
cq.Enqueue("First");
cq.Enqueue("Second");
cq.Enqueue("Third");
cq.Enqueue("Fourth");
cq.Enqueue("Fifth");
private void someMethod(string)
{
//do stuff
}
while (!cq.IsEmpty)
{
//how do I do the code below in a loop?
//inner loop starts here
someMethod(current cq item);
//move to the next item
someMethod(the next cq item);
//move to the next item
someMethod(the next cq item);
.
.
.
//if last item is reached, start from the top
}
请记住,应用程序用户可以随时在队列中添加或删除项目,即使 while 循环是 运行。
您应该将队列包装在 BlockingCollection
中(然后不直接访问底层队列)以获得一个允许您等待(阻塞)项目可用的线程安全队列。一旦你有了它,你可以使用 GetConsumingEnumerable()
如果你想遍历要处理的项目,或者只是为你想要的每个项目显式调用 Take
。
我正在使用 Winforms 并以 .Net 4.5 为目标
我想迭代并发队列,只要它有项目。在我的应用程序中,用户可以随时向并发队列添加和删除项目。
示例代码:
ConcurrentQueue<string> cq = new ConcurrentQueue<string>();
cq.Enqueue("First");
cq.Enqueue("Second");
cq.Enqueue("Third");
cq.Enqueue("Fourth");
cq.Enqueue("Fifth");
private void someMethod(string)
{
//do stuff
}
while (!cq.IsEmpty)
{
//how do I do the code below in a loop?
//inner loop starts here
someMethod(current cq item);
//move to the next item
someMethod(the next cq item);
//move to the next item
someMethod(the next cq item);
.
.
.
//if last item is reached, start from the top
}
请记住,应用程序用户可以随时在队列中添加或删除项目,即使 while 循环是 运行。
您应该将队列包装在 BlockingCollection
中(然后不直接访问底层队列)以获得一个允许您等待(阻塞)项目可用的线程安全队列。一旦你有了它,你可以使用 GetConsumingEnumerable()
如果你想遍历要处理的项目,或者只是为你想要的每个项目显式调用 Take
。