Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

C# Queue.TryDequeue: Safe Dequeue Without Exceptions

Learn how to use Queue<T>.TryDequeue in C# to safely dequeue items, handle empty queues without exceptions, and apply the same approach with ConcurrentQueue<T> in multithreaded code.

~5 min readC#
#Queue#TryDequeue#ConcurrentQueue#Exception Handling
Illustration of a C# Queue with TryDequeue returning a boolean and an out parameter.

When a Queue<T> might be empty, Queue<T>.TryDequeue lets you remove an item without throwing an exception. It returns bool: true if an item was dequeued, false if the queue was empty. The dequeued value is written to an out parameter. This makes it a natural choice for loops that process queue items until the queue is drained, especially when the queue might be empty at the start.

Understanding Queue<T>.TryDequeue

The Queue<T> class in System.Collections.Generic provides two ways to remove an item from the front of the queue: Dequeue() and TryDequeue(out T result). Dequeue() throws an InvalidOperationException if the queue is empty. TryDequeue does not throw; it returns false when there is nothing to dequeue. In that case, the out parameter is set to default(T).

The signature looks like this:

csharp
public bool TryDequeue(out T result)

When the queue has at least one element, TryDequeue removes the front element, assigns it to result, and returns true. When the queue is empty, it returns false and sets result to default(T) (null for reference types and the zero value for value types). This behavior is part of the API contract for this method.

Minimal Example: Draining a Queue Safely

A common use case is processing all items in a queue without knowing in advance whether the queue contains any. A loop that calls TryDequeue until it returns false handles both empty and non-empty queues without extra checks.

csharp
var queue = new Queue<string>(); queue.Enqueue("first"); queue.Enqueue("second"); while (queue.TryDequeue(out string item)) { Console.WriteLine(item); }

This loop prints first and second. If the queue had been empty, the loop would not execute at all, and no exception would be thrown. The inline out variable is a concise way to capture the dequeued value.

What Happens When the Queue Is Empty

When you call TryDequeue on an empty queue, it returns false and does not modify the queue. The out parameter receives the default value for the type. This is a deliberate design choice: it avoids exception-handling overhead and makes the control flow explicit.

Consider this code:

csharp
var queue = new Queue<int>(); bool success = queue.TryDequeue(out int value); Console.WriteLine($"Success: {success}, Value: {value}");

The output is Success: False, Value: 0. For reference types, value would be null. This behavior is useful when you want to treat an empty queue as a normal condition rather than an error.

TryDequeue with ConcurrentQueue<T>

The ConcurrentQueue<T> class in System.Collections.Concurrent also provides a TryDequeue method with the same signature and semantics. It is the thread-safe counterpart to Queue<T>. In a multithreaded environment, using ConcurrentQueue<T>.TryDequeue is the recommended way to consume items because it does not require external locking.

csharp
var concurrentQueue = new ConcurrentQueue<int>(); concurrentQueue.Enqueue(42); if (concurrentQueue.TryDequeue(out int result)) { Console.WriteLine(result); }

With multiple consumer threads, each item is obtained by exactly one thread: TryDequeue returns true on the thread that received the item. This makes it a reliable building block for producer-consumer patterns.

Common Mistakes and Edge Cases

One common mistake is ignoring the return value of TryDequeue. If you call TryDequeue and then use the out parameter without checking the Boolean, you may read a default value when the queue is empty. Always check the return value before using the dequeued item.

Another edge case involves value types. For a Queue<int>, an empty queue results in result being 0, which is indistinguishable from a real dequeued value of 0 if you do not check the return value. The same applies to bool, where false is the default. The return value is the only reliable indicator of success.

When working with ConcurrentQueue<T>, do not use the Count property to decide whether to call TryDequeue. The count can change between the check and the dequeue operation because other threads are modifying the queue. Always rely on the return value of TryDequeue to determine whether an item was obtained.

Performance Considerations

TryDequeue performs the same dequeue operation as Dequeue when an item is available, and the extra out parameter is normally negligible. Its practical benefit appears in the empty case: because it does not throw, there is no exception-handling overhead. If code repeatedly attempts to dequeue from a queue that is often empty, this can avoid the cost of constructing and unwinding exceptions.

For ConcurrentQueue<T>, TryDequeue is implemented for concurrent use and does not require the caller to take a lock. Its exact performance depends on the runtime and platform, but the method is intended for high-throughput producer-consumer scenarios.

Choosing Between TryDequeue, Dequeue, and Count Checks

Checking Count before calling Dequeue can avoid the exception, but the check-then-act pattern is not thread-safe when multiple threads access the queue, and it adds an extra operation even in the single-threaded case. TryDequeue combines the check and the removal in one call, which is both safer and more concise.

ApproachEmpty queue behaviorThread safetyExtra cost
Dequeue()Throws InvalidOperationExceptionNot thread-safeException handling if empty
Count + Dequeue()Avoids exception, but can race on a shared queueNot thread-safeCount check plus separate dequeue
TryDequeue()Returns falseOnly when backed by ConcurrentQueue<T>Minimal

Use TryDequeue when you expect the queue to be empty at times and want to handle that condition gracefully. Use Dequeue only when you are certain the queue is non-empty and an exception indicates a programming error.

Producer-Consumer Pattern with TryDequeue

A typical producer-consumer scenario uses a ConcurrentQueue<T> and one or more worker threads that call TryDequeue in a loop. The following example uses a cancellation flag so the consumer can stop when the producer is done. When the queue is temporarily empty, the consumer sleeps briefly instead of spinning tightly.

csharp
var queue = new ConcurrentQueue<int>(); var cts = new CancellationTokenSource(); // Producer Task.Run(() => { for (int i = 0; i < 100; i++) { queue.Enqueue(i); Thread.Sleep(10); } cts.Cancel(); }); // Consumer while (!cts.IsCancellationRequested) { if (queue.TryDequeue(out int item)) { Process(item); } else { Thread.Sleep(5); // avoid tight loop } }

This pattern works without knowing the exact number of items in advance. The TryDequeue return value is the source of truth for whether an item was available. If you need to ensure all items are processed after cancellation, add a final drain loop after the cancellation flag is set.

Compatibility Notes and Version Availability

Queue<T>.TryDequeue is available in .NET Core 2.0 and later, as well as in .NET Standard 2.1. It is not available in .NET Framework 4.8 or earlier, or in .NET Standard 2.0. In those environments, a single-threaded equivalent is:

csharp
if (queue.Count > 0) { var item = queue.Dequeue(); }

That pattern has a check-then-act race if multiple threads share the queue. For multithreaded code on older frameworks, use ConcurrentQueue<T>.TryDequeue, which has been available since .NET Framework 4.0. On modern .NET, you can use the same method name on both Queue<T> and ConcurrentQueue<T>, which makes it easy to switch between single-threaded and multithreaded contexts.

Try matching browser tools

All tools

Small utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.

All C# guides

More in C#

All C# guides

The guides filed next to this one in C#, in library order.