Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Async and Concurrency

System.Threading.Channels

Reference for System.Threading.Channels in C#: Channel.CreateBounded and CreateUnbounded, ChannelWriter, ChannelReader, completion and backpressure.

A Channel<T> is an asynchronous, thread-safe queue designed for producer-consumer pipelines. Producers write items with a ChannelWriter<T>; consumers read them with a ChannelReader<T> and await when nothing is available. Nobody blocks a thread while waiting.

A bounded channel has a fixed capacity: when it is full, writers wait. That is called backpressure, and it keeps a fast producer from overrunning a slow consumer. An unbounded channel never makes writers wait but can grow without limit. The types live in the System.Threading.Channels namespace (part of the shared framework, no package needed).

C#
using System.Threading.Channels;

var channel = Channel.CreateBounded<int>(10);
await channel.Writer.WriteAsync(1);
int item = await channel.Reader.ReadAsync();

Try it

C# Producer and consumer

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.

C# Full modes, TryWrite and several consumers

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

C#
public static class Channel
{
    public static Channel<T> CreateUnbounded<T>();
    public static Channel<T> CreateUnbounded<T>(UnboundedChannelOptions options);
    public static Channel<T> CreateBounded<T>(int capacity);
    public static Channel<T> CreateBounded<T>(BoundedChannelOptions options);
}

public abstract class Channel<T>
{
    public ChannelReader<T> Reader { get; }
    public ChannelWriter<T> Writer { get; }
}

public abstract class ChannelWriter<T>
{
    public abstract bool TryWrite(T item);
    public virtual ValueTask WriteAsync(T item, CancellationToken ct = default);
    public abstract ValueTask<bool> WaitToWriteAsync(CancellationToken ct = default);
    public bool TryComplete(Exception? error = null);
    public void Complete(Exception? error = null);
}

public abstract class ChannelReader<T>
{
    public abstract bool TryRead(out T item);
    public virtual ValueTask<T> ReadAsync(CancellationToken ct = default);
    public abstract ValueTask<bool> WaitToReadAsync(CancellationToken ct = default);
    public virtual IAsyncEnumerable<T> ReadAllAsync(CancellationToken ct = default);
    public virtual Task Completion { get; }
}
Name Description
capacity Maximum number of queued items in a bounded channel.
FullMode Wait (default), DropOldest, DropNewest or DropWrite.
SingleReader, SingleWriter Promise that only one reader or writer exists; allows faster implementations.
AllowSynchronousContinuations Run reader continuations inline in the writer's call. Faster, but riskier.
error Optional exception delivered to readers when the channel completes.

Returns: TryWrite and TryRead return true on success. WaitToReadAsync returns false once the channel is completed and empty. Completion finishes when the writer is completed and all items have been read.

Errors: WriteAsync throws ChannelClosedException after completion. ReadAsync throws ChannelClosedException when the channel is completed and empty; if Complete(error) was used, the error is its InnerException.

Usage notes

  • Always complete the writer. ReadAllAsync and Completion never finish if nobody calls Complete(). With several producers, complete once after all of them are done (for example after Task.WhenAll).
  • Prefer bounded channels in services: capacity gives you backpressure and a memory limit. Use Wait mode unless dropping data is acceptable.
  • TryWrite on a full Wait-mode channel returns false; it does not wait. Use WriteAsync to wait.
  • Each item is delivered once. Several readers share the work (competing consumers). To give every consumer every item, use one channel per consumer.
  • Hide the other half. Expose only Reader to consumers and only Writer to producers, so the roles are enforced by types.
  • Cancellation. Pass a CancellationToken to WriteAsync and ReadAllAsync so shutdown does not hang on a full or empty channel.
  • Compared with BlockingCollection<T>, channels are async all the way down and have no blocking calls, so they scale better in server code. See BlockingCollection.
  • Order is first in, first out for a single writer; items from several writers interleave arbitrarily.