3

我正在使用 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 循环运行时也是如此。

4

1 回答 1

2

您应该将队列包装在一个BlockingCollection(然后不直接访问底层队列)以拥有一个线程安全队列,该队列允许您等待(阻塞)一个项目变得可用。一旦你有了它,GetConsumingEnumerable()如果你想循环处理要处理的项目,或者只是Take为你想要的每个项目显式调用,你就可以使用它。

于 2015-05-14T20:50:56.693 回答