An unbounded channel has a hidden problem. If items arrive faster than they're handled, the queue grows until the program runs out of memory. Backpressure is the answer: a full queue tells the producer to slow down. Without it, an overloaded system doesn't slow down, it collapses.
A bounded channel
Channel.CreateBounded<T>(capacity) holds at most that many items. WriteAsync waits when it's full, and resumes when a reader makes room. Follow the order below, which shows the writer pausing. A capacity of 1 lets the writer get one item ahead of the reader.
using System.Threading.Channels;
Channel<int> channel = Channel.CreateBounded<int>(1);
Task writer = WriteAsync();
await Task.Delay(20);
Console.WriteLine("reader starts");
await foreach (int value in channel.Reader.ReadAllAsync())
{
Console.WriteLine($"read {value}");
await Task.Delay(20);
}
await writer;
async Task WriteAsync()
{
for (int i = 0; i < 2; i++)
{
await channel.Writer.WriteAsync(i);
Console.WriteLine($"wrote {i}");
}
channel.Writer.Complete();
}Check your prediction
wrote 0
reader starts
read 0
wrote 1
read 1The writer stopped until the reader made space, and nothing grew without limit. With a real source, the same pause spreads upstream: stop reading the file or the socket, and the sender slows too.
Proving it with a lazy source
Pulling from an IEnumerable shows how far a producer got. With capacity 2 and a blocked worker, it can't get far. The job runner's checks use this exact test, with a TaskCompletionSource as a gate: its task doesn't finish until you say so.
using System.Threading.Channels;
Channel<int> channel = Channel.CreateBounded<int>(2);
var gate = new TaskCompletionSource();
int pulled = 0;
Task producer = ProduceAsync();
Task consumer = ConsumeAsync();
await Task.Delay(20);
Console.WriteLine(pulled);
gate.SetResult();
await Task.WhenAll(producer, consumer);
Console.WriteLine(pulled);
IEnumerable<int> Source()
{
for (int i = 0; i < 100; i++)
{
pulled++;
yield return i;
}
}
async Task ProduceAsync()
{
foreach (int item in Source())
{
await channel.Writer.WriteAsync(item);
}
channel.Writer.Complete();
}
async Task ConsumeAsync()
{
await foreach (int item in channel.Reader.ReadAllAsync())
{
await gate.Task;
}
}Check your prediction
4
100Four items: one held by the blocked consumer, two in the channel, and one waiting at WriteAsync.
When waiting isn't an option
Sometimes it's better to lose data than to wait. A telemetry feed wants the newest value, not a growing delay. BoundedChannelFullMode sets what happens when it's full. Predict what's left in each channel after writing 1, 2 and 3 with room for two.
using System.Threading.Channels;
foreach (var mode in new[] { BoundedChannelFullMode.DropOldest, BoundedChannelFullMode.DropNewest, BoundedChannelFullMode.DropWrite })
{
var channel = Channel.CreateBounded<int>(new BoundedChannelOptions(2) { FullMode = mode });
foreach (int value in new[] { 1, 2, 3 })
{
channel.Writer.TryWrite(value);
}
channel.Writer.Complete();
var kept = new List<int>();
await foreach (int value in channel.Reader.ReadAllAsync())
{
kept.Add(value);
}
Console.WriteLine($"{mode}: {string.Join(",", kept)}");
}Check your prediction
DropOldest: 2,3
DropNewest: 1,3
DropWrite: 1,2| Mode | Use when |
|---|---|
Wait (default) | Every item matters, and waiting is acceptable |
DropOldest | Only the most recent values matter |
DropWrite | What's already queued matters more than what's new |
TryWrite with Wait returns false when full, which suits a server that wants to reply "too busy" rather than queue a request it may never reach. The Drop modes throw items away silently, so count them if you need to know. A callback overload of CreateBounded tells you about each one.
Choosing a capacity
Bigger isn't better. A buffer smooths bursts, but it also hides overload and adds delay, because each item waits behind everything queued before it. Start small, a few times the number of workers, and raise it only if measurements show the workers going idle while work is on its way. The job runner defaults to a capacity of 4, with 2 workers.
Your turn
Shed load when full
Write Throttle<T>, which accepts items through a bool Offer(T item) method. Offer returns false when the buffer is full, without waiting, and counts it in Rejected. A RunAsync(Func<T, Task> handler) method handles items one at a time until Finish() is called and everything has been handled, and counts Handled.
With capacity 2, offer 5 items before starting RunAsync, and print each result of Offer. Call Finish, then run with a handler that records the items. Print the items, Rejected and Handled. Finally, Offer after Finish must return false, without counting as a rejection: the throttle is closed, not full.
When it works, it prints:
True
True
False
False
False
1,2
3
2
Falseusing System.Threading.Channels;
var channel = Channel.CreateBounded<int>(new BoundedChannelOptions(2) { FullMode = BoundedChannelFullMode.Wait });
Console.WriteLine(channel.Writer.TryWrite(1));Hint 1: the idea
TryWrite already has most of the behaviour you want from Offer. It returns false both when the channel is full and when it's been completed, so Offer has to tell those two apart before counting a rejection.
Hint 2: a first step
Wrap a bounded channel in the class, and make Finish call Writer.Complete. Then RunAsync is a single await foreach.
Show one solution
using System.Threading.Channels;
var throttle = new Throttle<int>(2);
foreach (int value in new[] { 1, 2, 3, 4, 5 })
{
Console.WriteLine(throttle.Offer(value));
}
throttle.Finish();
var seen = new List<int>();
await throttle.RunAsync(async item =>
{
await Task.Yield();
seen.Add(item);
});
Console.WriteLine(string.Join(",", seen));
Console.WriteLine(throttle.Rejected);
Console.WriteLine(throttle.Handled);
Console.WriteLine(throttle.Offer(6));
class Throttle<T>(int capacity)
{
private readonly Channel<T> channel = Channel.CreateBounded<T>(capacity);
public int Rejected { get; private set; }
public int Handled { get; private set; }
private bool finished;
public bool Offer(T item)
{
if (finished)
{
return false;
}
bool accepted = channel.Writer.TryWrite(item);
if (!accepted)
{
Rejected++;
}
return accepted;
}
public void Finish()
{
finished = true;
channel.Writer.Complete();
}
public async Task RunAsync(Func<T, Task> handler)
{
await foreach (T item in channel.Reader.ReadAllAsync())
{
await handler(item);
Handled++;
}
}
}True
True
False
False
False
1,2
3
2
FalseThis is load shedding rather than rate limiting: when the buffer is full, extra work is turned away, not slowed down. The finished flag keeps a closed throttle's refusals out of Rejected, so that count means only one thing: work turned away for lack of room.
Completion is saved in this browser only. It does not measure mastery.