ConcurrentQueue | ConcurrentStack | ConcurrentBag | |
---|---|---|---|
Order | First-in-First-out | Last-in-First-out | Order is unspecified Based on performance. Effecient if same threads are adding and removing. |
Add Item | Enqueue() | Push() | Add() |
Remove Item | TryDequeue() | TryPop() | TryTake() |
To avoing polling we can use BlockingCollection
Multiple threads or tasks can add items to the collection concurrently, and if the collection reaches its specified maximum capacity, the producing threads will block until an item is removed. Multiple consumers can remove items concurrently, and if the collection becomes empty, the consuming threads will block until a producer adds an item. A producing thread can call
CompleteAdding
to indicate that no more items will be added. Consumers monitor theIsCompleted
property to know when the collection is empty and no more items will be added.
BlockingCollection<T>
provides a GetConsumingEnumerable method that enables consumers to useforeach
(For Each
in Visual Basic) to remove items until the collection is completed, which means it is empty and no more items will be added.