liveBook · Manning

ConcurrentQueue<T>

As explained in C# Concurrency: Asynchronous and multithreaded programming

ConcurrentQueue<T> is a .NET thread-safe generic FIFO collection that supports concurrent item insertion and removal.

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

How C# Concurrency: Asynchronous and multithreaded programming covers it

How deep it goes
Explains FIFO behavior and race-free TryDequeue usage, without detailing the collection’s internal implementation.
Examples
Contrasts Queue<T> Count-plus-Dequeue with ConcurrentQueue<T> TryDequeue.
What it assumes
Assumes familiarity with Queue<T> and teaches why separate availability checks become unsafe across threads.
What you can do after
Apply it via Enqueue and TryDequeue to coordinate concurrent queue access without a check-then-remove race.
How it connects
Connects ConcurrentQueue<T> with Queue<T>, BlockingCollection<T>, producer–consumer processing, and asynchronous programming.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of C# Concurrency: Asynchronous and multithreaded programming. The section links point to the parts of the book it draws on.