Multiple consumers and querying a C# BlockingCollection

后端 未结 2 482
半阙折子戏
半阙折子戏 2021-02-05 08:14

I am using a .NET 4.0 BlockingCollection to handle a queue of items that each need to be processed by an operation that can take up to a second to process each item. This queue

2条回答
  •  梦如初夏
    2021-02-05 08:16

    GetConsumingEnumerable is in fact safe to call from multiple consumers simultaneously; the enumerable only completes when the collection is marked as complete. Each item is only consumed once.

    GetConsumingEnumerable is essentially equivalent to:

    while (!IsCompleted)
    {
      if (TryTake(out var item, Timeout.Infinite))
        yield return item;
    }
    

    plus a bit of cancellation/cleanup logic.

提交回复
热议问题