Codectionary / Developer documentation / C#

Connect Producers and Consumers with Channels

Use a bounded in-process queue to coordinate asynchronous production, consumption and completion.

Read the syntax

Use a bounded in-process queue to coordinate asynchronous production, consumption and completion.

The caller starts reading before awaiting producer completion, avoiding the single-consumer deadlock described above.

What it is and why to use it

A producer and consumer may work at different rates. System.Threading.Channels provides asynchronous queues between them. A bounded channel limits queued item count and, with Wait mode, applies backpressure when it is full. The shared .NET framework includes Channels in modern .NET, so these .NET 10 examples need no additional package.

How it works

Create a channel, send items through its Writer and consume through its Reader. In bounded Wait mode, WriteAsync can wait for space. ReadAllAsync finishes after the writer completes and buffered data has been consumed. TryWrite reports immediate acceptance without waiting. A real pipeline must propagate completion errors and cancellation and await its producer tasks.

Common mistakes and limitations

Do not await a blocked producer to finish before starting the only consumer of a full bounded channel. Do not forget completion, which can leave readers waiting indefinitely. Item capacity is not a byte limit, and in-memory channels are not durable message brokers or cross-process queues.

Run the examples locally

These complete Program.cs examples use a .NET 10 console project with the C# language version set to 12.0, nullable checking enabled and implicit usings disabled. They use standard .NET libraries and need no extra NuGet packages. This is the verified environment, not a claim that every API requires .NET 10 or works unchanged in .NET Framework, Unity or other runtimes.

Install a supported .NET 10 SDK, create the console project, replace its project file with the settings below, then replace Program.cs with one complete example at a time. Build and run from the project folder. using directives bring namespaces into scope; top-level statements form the program’s entry point, and any helper types follow those statements. Console.WriteLine writes terminal output. Do not combine examples that declare the same type names.

C# in Codectionary’s Playground is editing-only: it does not compile or execute these programs. Run them with the local .NET SDK to reproduce the expected output. Async examples use controlled in-process operations rather than live network services or timing-sensitive delays.

Create and enter a project

dotnet new console -n CSharpExample --framework net10.0
cd CSharpExample

CSharpExample.csproj settings used for these examples

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <LangVersion>12.0</LangVersion>
    <Nullable>enable</Nullable>
    <ImplicitUsings>disable</ImplicitUsings>
  </PropertyGroup>
</Project>

Build and run after saving one example in Program.cs

dotnet build
dotnet run --no-build

Continue learning

Change one input and predict the result before running it. Follow the related guides to connect this topic with the surrounding language features.

Syntax

var channel = Channel.CreateBounded<int>(1);
await channel.Writer.WriteAsync(value);

Examples

Run a bounded producer and consumer together

Use one slot while allowing consumption to free space for the next write.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Channels;

var channel = Channel.CreateBounded<int>(new BoundedChannelOptions(1) { FullMode = BoundedChannelFullMode.Wait });
Task producer = Produce();
try {
    await foreach (int value in channel.Reader.ReadAllAsync()) Console.WriteLine(value);
} finally { await producer; }
async Task Produce() {
    try {
        await channel.Writer.WriteAsync(1);
        await channel.Writer.WriteAsync(2);
        channel.Writer.Complete();
    } catch (Exception error) {
        channel.Writer.TryComplete(error);
        throw;
    }
}
  1. The first write can fill the slot and the second can wait until the reader frees space.
  2. The caller starts reading before awaiting producer completion, avoiding the single-consumer deadlock described above.
  3. Completing the writer lets ReadAllAsync finish after draining, and the finally observes producer completion. A real pipeline also needs coordinated cancellation if its consumer stops early.
  4. Expected output: 1 2
  5. Choose capacity and full-mode behaviour deliberately.

Inspect immediate bounded writes

Distinguish a full queue from an asynchronously waiting write.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Channels;

var channel = Channel.CreateBounded<int>(1);
Console.WriteLine(channel.Writer.TryWrite(10));
Console.WriteLine(channel.Writer.TryWrite(20));
Console.WriteLine(await channel.Reader.ReadAsync());
channel.Writer.Complete();
  1. TryWrite accepts 10 because the one slot is initially free.
  2. The second TryWrite returns false rather than waiting for the full slot.
  3. Reading retrieves 10 and the writer is explicitly completed. A failed TryWrite requires the producer’s chosen retry, wait or rejection policy.
  4. Expected output: True False 10
  5. Choose capacity and full-mode behaviour deliberately.

Best practices

  • Choose capacity and full-mode behaviour deliberately.
  • Propagate cancellation, completion and failures across the entire pipeline.

Runtime & versions

.NET runtime. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

C# language reference

Specifications & further reading