如何重复迭代并发队列?

时间:2015-05-14 20:47:44

标签: c# winforms concurrent-queue

我正在使用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循环正在运行,应用程序用户也可以随时在队列中添加或删除项目。

1 个答案:

答案 0 :(得分:2)

您应该将队列包装在BlockingCollection中(然后不直接访问底层队列)以拥有一个线程安全队列,允许您等待(阻止)项目可用。完成后,如果要循环处理要处理的项目,可以使用GetConsumingEnumerable(),或者只为每个项目明确调用Take