Channels and backpressure
Channels and backpressure
A channel is an asynchronous handoff between producers, which submit items, and consumers, which process them. A bounded channel limits the number of buffered items. With the Wait full mode, a writer awaits space rather than continuously allocating more queue entries. This is backpressure: a slow downstream stage constrains the upstream stage. It is not a bound on total application memory; item size, active workers, and other queues also matter. Choose a capacity from workload measurements and latency requirements, not an arbitrary claim about throughput.
Baseline: .NET 10 / C# 14 (SDK candidate inherited, not installed). Each example is an independent project with predicted output. Build and runtime verification are pending. Run only a reviewed fixture in an approved disposable environment.
Observe backpressure without a sleep
Fill a capacity-two channel, then start a third write. No reader runs until after the first observation.
using System;using System.Threading.Channels;var queue = Channel.CreateBounded<int>(2);await queue.Writer.WriteAsync(10);await queue.Writer.WriteAsync(20);var pending = queue.Writer.WriteAsync(30);Console.WriteLine(pending.IsCompleted);Console.WriteLine(await queue.Reader.ReadAsync());await pending;queue.Writer.Complete();await foreach (int value in queue.Reader.ReadAllAsync()) Console.WriteLine(value);The third write cannot finish while both slots are occupied. Reading 10 makes space. Completion ends further writes but preserves accepted entries for the reader.
Expected observation (reasoned, not executed):
False102030Choose explicit loss for replaceable readings
For display-only readings, keeping recent values may be more useful than keeping every sample. This policy is not suitable for payments or other durable events.
using System;using System.Threading.Channels;var queue = Channel.CreateBounded<int>(new BoundedChannelOptions(2){ FullMode = BoundedChannelFullMode.DropOldest});foreach (int reading in new[] { 10, 20, 30 }) Console.WriteLine(queue.Writer.TryWrite(reading));queue.Writer.Complete();await foreach (int reading in queue.Reader.ReadAllAsync()) Console.WriteLine(reading);Successful writes under a dropping policy do not prove every item was retained. The oldest buffered reading was evicted.
Expected observation (reasoned, not executed):
TrueTrueTrue2030Separate producer and consumer ownership
A single producer owns writer completion. A single consumer keeps its own total. Both operations are observed.
using System;using System.Threading.Channels;using System.Threading.Tasks;var queue = Channel.CreateBounded<int>(2);async Task ProduceAsync(){ try { foreach (int value in new[] { 2, 4, 6, 8 }) await queue.Writer.WriteAsync(value); queue.Writer.Complete(); } catch (Exception error) { queue.Writer.TryComplete(error); throw; }}async Task<int> ConsumeAsync(){ int total = 0; await foreach (int value in queue.Reader.ReadAllAsync()) total += value; return total;}Task<int> consumer = ConsumeAsync();Task producer = ProduceAsync();await Task.WhenAll(producer, consumer);Console.WriteLine(await consumer);Both tasks are started before either is awaited to completion. The finite consumer cannot fail on these inputs; production systems need shared cancellation for consumer failures (chapter lesson 3).
Expected observation (reasoned, not executed):
20Common mistakes and design limits
An unbounded channel does not automatically slow a producer. In Wait mode, TryWrite can return false when full; do not spin until it succeeds. Await WriteAsync or WaitToWriteAsync, checking the result and retrying because another writer may acquire the space. DropNewest removes the newest queued item; DropWrite discards the incoming item. DropOldest evicts the oldest queued item. Under dropping policies, TryWrite can return true even if an item is lost. For bounded drop accounting, supply an itemDropped callback when creating the channel; keep it short, nonthrowing and safe for concurrent calls in a multiwriter design. A single-reader/writer option is a promise about usage, not a way to enforce exclusivity.
Apply the concept
Trace a capacity-two Wait channel with writes 7, 8, 9. Then repeat using DropOldest. Explain which writes finish before any read and which items are eventually read.
Check your work: Wait: 7 and 8 finish; 9 waits until 7 is read, and the final read order is 7, 8, 9. DropOldest: all three writes finish; 8 and 9 remain.
Further study
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Channels and backpressure — knowledge check
Apply the lesson concepts to the following scenarios.
A Wait channel is full. What happens to WriteAsync?
Which values remain after writing 1, 2, 3 to an unread capacity-two DropOldest channel?
Does a capacity of two bound the total bytes in a service?
What does normal writer completion do?
Why await both producer and consumer tasks?