Channels
A channel is a queue between producers and consumers where the wait is asynchronous. The writer gets a task from WriteAsync and the reader from ReadAsync, and neither blocks a thread. A channel can be bounded, which gives the producer back pressure, or unbounded, which never makes it wait.
A channel and its writer
The program creates a channel that holds two items, writes four from a background task, completes the writer and consumes the reader as an async stream:
using System.Threading.Channels;
var channel = Channel.CreateBounded<int>(2);
var writer = Task.Run(async () =>
{
for (var i = 1; i <= 4; i++)
{
await channel.Writer.WriteAsync(i);
}
channel.Writer.Complete();
});
var total = 0;
await foreach (var item in channel.Reader.ReadAllAsync())
{
total += item;
}
await writer;
Console.WriteLine($"total {total}");
Console.WriteLine($"completed {channel.Reader.Completion.IsCompleted}");
dotnet run
total 10
completed True
The sum is the four numbers and the reader completed, because the writer called Complete after the last write. ReadAllAsync returns an IAsyncEnumerable<T>, which the previous part covered: the loop awaits each item and ends when the channel is completed and empty. The bound of two made the writer wait on the third write until the reader had taken one.
A bounded channel
The bound is the number of items in the buffer, not the number of writers. WriteAsync returns a task that completes when there is room; a writer that ignores the task keeps producing in memory and the bound does nothing. A program that must never drop an item awaits every write, as the example does; a program that may drop one uses TryWrite and reads its boolean.
using System.Threading.Channels;
var channel = Channel.CreateBounded<int>(1);
Console.WriteLine($"write {channel.Writer.TryWrite(1)}");
Console.WriteLine($"full {channel.Writer.TryWrite(2)}");
Console.WriteLine($"read {channel.Reader.TryRead(out var first)}");
Console.WriteLine($"first {first}");
Console.WriteLine($"again {channel.Writer.TryWrite(3)}");
channel.Writer.Complete();
Console.WriteLine($"done {channel.Reader.Completion.IsCompleted}");
dotnet run
write True
full False
read True
first 1
again True
done False
The first write fit, the second did not, and it was dropped because TryWrite does not wait. Reading freed the slot, so the third write fit. Completion is not completed yet even though the writer was completed: one item is still in the channel, and the completion task finishes when the channel is empty. A program that completes the writer and then drops the reader leaks the items.
Reading without waiting
An unbounded channel never makes the writer wait. The reader can ask whether anything is available with WaitToReadAsync and take what is there with TryRead:
using System.Threading.Channels;
var channel = Channel.CreateUnbounded<string>();
await channel.Writer.WriteAsync("a");
await channel.Writer.WriteAsync("b");
channel.Writer.Complete();
Console.WriteLine(await channel.Reader.WaitToReadAsync());
while (channel.Reader.TryRead(out var item))
{
Console.WriteLine($"read {item}");
}
Console.WriteLine($"done {channel.Reader.Completion.IsCompleted}");
dotnet run
True
read a
read b
done True
WaitToReadAsync returned true at once, because the items were already there. The loop kept taking until TryRead was false, and the completion was true after the last item left an empty channel. A real reader wraps these two calls in a loop: wait, drain, repeat, and stop when WaitToReadAsync returns false.
Channel or blocking collection
- A channel is the choice in async code: the wait is a task, so a consumer does not hold a thread.
- A BlockingCollection is the choice in code that already has dedicated threads, and it predates the async streams.
- A channel carries one reader by default; several readers may share it, and each item goes to exactly one of them.
- Closing is the writer calling Complete; a reader cannot close a channel.
Exercises
- Give a bounded channel of one item to two writers and watch them take turns.
- Read the same channel with two consumers and count the items each one took.
- Use TryWrite in the first program and count the dropped items.
- Complete a channel with an item still in it and read Completion before and after the item is taken.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which namespace holds Channel<T>?
Answer
System.Threading.Channels
The types are in the shared framework, with no package needed.
-
What does Channel.CreateBounded<int>(2) mean?
Answer
At most two items wait in the buffer
The bound is the capacity, and WriteAsync waits when it is full.
-
What does this program print?
using System.Threading.Channels; var channel = Channel.CreateBounded<int>(2); var writer = Task.Run(async () => { for (var i = 1; i <= 4; i++) await channel.Writer.WriteAsync(i); channel.Writer.Complete(); }); var total = 0; await foreach (var item in channel.Reader.ReadAllAsync()) total += item; await writer; Console.WriteLine(total);Answer
10
The four numbers are 1, 2, 3 and 4, and the reader takes all of them.
-
What does Writer.Complete do?
Answer
Stops further writes and lets the reader finish
The reader completes when the channel is completed and empty.
-
What does this program print?
using System.Threading.Channels; var channel = Channel.CreateUnbounded<string>(); await channel.Writer.WriteAsync("a"); Console.WriteLine(await channel.Reader.WaitToReadAsync());Answer
True
An item is waiting, so the task completes with true.
-
What does Reader.ReadAllAsync return?
Answer
An IAsyncEnumerable<T> over the items
It is consumed by await foreach and ends when the channel completes.
-
What does WriteAsync do when a bounded channel is full?
Answer
Returns a task that completes when there is room
The bound produces back pressure through the awaited task.
-
What does Reader.TryRead return?
Answer
A boolean, with the item in an out parameter
The measured call returned true and put the value in first.
-
What does this program print?
using System.Threading.Channels; var channel = Channel.CreateBounded<int>(1); channel.Writer.TryWrite(1); channel.Writer.TryWrite(2); Console.WriteLine(channel.Reader.TryRead(out var value)); Console.WriteLine(value);Answer
True and then 1
The first write is the one in the channel; the second was dropped.
-
How does a consumer stop a channel?
Answer
It does not, only the writer completes the channel
Completion belongs to the writer; the reader observes it.
The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev