如何重复迭代并发队列?

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 循环正在运行。

当假设您的ConcurrentQueue为空(所有项目都已消耗)并添加新项目时会发生什么?根据您的要求,它应该自动被消耗吗? - Michael
我甚至还没有想那么远,但是可以。我可能可以通过一个计时器来解决这个问题,它检查集合是否有项目,如果有,就开始循环,如果它还没有运行。 - TH Todorov
1个回答

2

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接