ConcurrentQueue
Learn the thread-safe queue with ConcurrentQueue.
ConcurrentQueue
ConcurrentQueue<T> is a thread-safe first-in-first-out (FIFO) queue. Many threads can call Enqueue and TryDequeue at once; the contents stay consistent without locking.
It uses a lock-free linked list internally. In producer-consumer scenarios, threads add tasks to the queue and drain them from a pool.
TryDequeue and TryPeek
TryDequeue(out T item) removes the front item and returns true; if the queue is empty it returns false instead of throwing. This is the safe way to poll an empty queue.
TryPeek(out T item) looks at the front without removing it. In a loop, while (queue.TryDequeue(out var x)) drains every item in order.
Exercise Enqueue and drain the queue
The queue below is empty. Use Enqueue to add three items: "a", "b", "c". Then loop with while (queue.TryDequeue(out var item)) and print each item with Console.WriteLine(item).
Show example solution
queue.Enqueue("a"); queue.Enqueue("b"); queue.Enqueue("c"); Then while (queue.TryDequeue(out var item)) Console.WriteLine(item);
Example solution:
using System;
using System.Collections.Concurrent;
class Program
{
static void Main()
{
var queue = new ConcurrentQueue<string>();
queue.Enqueue("a");
queue.Enqueue("b");
queue.Enqueue("c");
while (queue.TryDequeue(out var item))
{
Console.WriteLine(item);
}
}
}
Test yourself
-
Complete the Enqueue call
queue.____;Show answer
queue.Enqueue("task"); -
Which method removes an item from a ConcurrentQueue?
- Pop
- Remove
- Take
- TryDequeue
Show answer
TryDequeue — Correct. TryDequeue safely removes the front item.
-
Match each queue method
- Enqueue
- Add to the back
- TryDequeue
- Remove from front
- TryPeek
- Look at front without removing