C# Reference ยท Collections
BlockingCollection and Channels
Reference for producer-consumer queues in C#: BlockingCollection<T> with bounded capacity and the async-friendly Channel<T>, completion and cancellation.
A producer-consumer queue lets one part of a program add work while another part takes it, with the queue handling waiting. .NET has two main tools. BlockingCollection<T> (namespace System.Collections.Concurrent) is the older, thread-blocking one: Take() waits on an OS thread until an item exists. Channel<T> (namespace System.Threading.Channels) is newer and built for async/await: reads and writes are awaited and no thread sits blocked.
Both can be bounded, so a fast producer is slowed down instead of filling memory. Both have a "no more items" signal (CompleteAdding and Writer.Complete) which lets the consumer finish its loop cleanly. For new code, prefer channels.
using System.Threading.Channels; var channel = Channel.CreateUnbounded<int>(); await channel.Writer.WriteAsync(42); int item = await channel.Reader.ReadAsync();
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
// System.Threading.Channels Channel<T> Channel.CreateUnbounded<T>(); Channel<T> Channel.CreateBounded<T>(int capacity); Channel<T> Channel.CreateBounded<T>(BoundedChannelOptions options); ChannelWriter<T>: ValueTask WriteAsync(T item, CancellationToken ct = default); bool TryWrite(T item); bool TryComplete(Exception? error = null); void Complete(Exception? error = null); ChannelReader<T>: ValueTask<T> ReadAsync(CancellationToken ct = default); bool TryRead(out T item); IAsyncEnumerable<T> ReadAllAsync(CancellationToken ct = default); Task Completion { get; } // System.Collections.Concurrent public class BlockingCollection<T> : IDisposable { public BlockingCollection(); public BlockingCollection(int boundedCapacity); public void Add(T item); public bool TryAdd(T item, int millisecondsTimeout); public T Take(); public bool TryTake(out T item, int millisecondsTimeout); public void CompleteAdding(); public IEnumerable<T> GetConsumingEnumerable(); public bool IsCompleted { get; } public bool IsAddingCompleted { get; } }
| Name | Description |
|---|---|
capacity / boundedCapacity |
Maximum queued items. Adding to a full collection waits (or TryAdd times out). |
BoundedChannelOptions.FullMode |
What a full bounded channel does: Wait (default), DropOldest, DropNewest or DropWrite. |
SingleReader, SingleWriter |
Channel options that allow faster internal code when you promise one reader or writer. |
CancellationToken |
Cancels a pending read or write with OperationCanceledException. |
Returns: ReadAsync and Take return the next item. TryRead, TryTake and TryWrite return false instead of waiting. ReadAllAsync and GetConsumingEnumerable yield items until the producer completes and the queue is drained.
Errors: ChannelClosedException when you read from a completed, empty channel with ReadAsync (ReadAllAsync just ends), or write after completion. InvalidOperationException when Add is called after CompleteAdding, or Take on a completed, empty BlockingCollection. Passing an error to Complete(ex) surfaces ex to readers.
Usage notes
- Always complete the writer. A consumer in
await foreachorGetConsumingEnumerable()waits forever if nobody callsComplete/CompleteAdding. Put the call in afinallyblock on the producer side. - Backpressure. Use a bounded capacity so producers cannot outrun consumers. For a channel,
FullModelets you drop items instead of waiting, which suits telemetry or latest-value-wins cases. - Blocking versus async.
BlockingCollection.Takeblocks a thread; in an ASP.NET Core or UI app, that can starve the thread pool. Channels never block threads when used withawait. - Several consumers can read the same channel; each item goes to exactly one reader. Use one channel per consumer group if everyone must see every item.
- Ordering: both are FIFO by default.
BlockingCollection<T>can wrap aConcurrentStack<T>orConcurrentBag<T>for other orders. - Disposal:
BlockingCollection<T>isIDisposable; channels are not. - Plain
Queue<T>is not thread-safe. Do not share it without a lock; a channel is the safer replacement.