【问题标题】:How do I iterate concurrent queue repeatedly?如何反复迭代并发队列?
【发布时间】:2015-07-26 15:27:09
【问题描述】:

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

【问题讨论】:

  • 假设您的并发队列为空(所有项目都被消耗)并添加了新项目时会发生什么?是否应该根据您的要求自动使用?
  • 我还没有想到那么远,但是是的。我可以用一个计时器来解决这个问题,它检查集合是否有项目,如果有,如果它还没有运行,就启动循环。

标签: c# winforms concurrent-queue


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-29
    • 2020-09-02
    • 1970-01-01
    • 1970-01-01
    • 2018-09-23
    • 2019-11-17
    • 2019-01-15
    相关资源
    最近更新 更多