ConcurrentQueue<T> is a thread-safe FIFO collection for concurrent producers and consumers. It preserves insertion order while avoiding the race window created by checking Count before dequeuing. section 13.2.4 section 13.5
Use the queue when multiple threads share work and need these guarantees:
- Enqueue items with the queue operation corresponding to Queue<T>. Enqueue. section 13.2.4
- Remove the next item with TryDequeue, which combines availability checking and removal into one operation. section 13.2.4
- Use the collection directly when consumers should not block while waiting for work; add BlockingCollection<T> when blocking or bounded capacity is required. section 13.2.2 section 13.2.6
- Use it from asynchronous or non-asynchronous code, but avoid treating BlockingCollection<T> as an asynchronous abstraction. section 13.2.6
var queue = new ConcurrentQueue<int>();
// ....
if(queue.TryDequeue(out var next)) #1
{
// use next
}
Prefer TryDequeue over a separate Count check and Dequeue call because another thread can remove the final item between those operations. section 13.2.4
