C# 如何重复迭代并发队列?

C# 如何重复迭代并发队列?,c#,winforms,concurrent-queue,C#,Winforms,Concurrent Queue,我正在使用Winforms和targeting.NET4.5 我想迭代并发队列,只要它有项目。在我的应用程序中,用户可以随时向并发队列添加和删除项目 示例代码: ConcurrentQueue<string> cq = new ConcurrentQueue<string>(); cq.Enqueue("First"); cq.Enqueue("Second"); cq.Enqueue("Third"); cq.Enqueue("Fourth"); cq.Enqueue

我正在使用Winforms和targeting.NET4.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

}
ConcurrentQueue cq=新的ConcurrentQueue();
cq.排队(“第一”);
cq.排队(“第二”);
cq.排队(“第三”);
cq.排队(“第四”);
cq.排队(“第五”);
私有方法(字符串)
{
//做事
}
而(!cq.IsEmpty)
{
//如何在循环中执行下面的代码?
//内部循环从这里开始
someMethod(当前cq项);
//移到下一项
someMethod(下一个cq项);
//移到下一项
someMethod(下一个cq项);
. 
.
.
//如果到达最后一项,则从顶部开始
}

请记住,应用程序用户可以随时从队列中添加或删除项目,即使while循环正在运行。

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

如果你的concurrentqueue是空的(所有项目都被消耗了)并且添加了新项目,会发生什么?它应该被你的需求自动消耗掉吗?我甚至还没有想到,但是是的。我可能可以通过一个计时器来解决这个问题,该计时器检查集合是否有项,如果有项,则在尚未运行时启动循环。