C#
ChannelReader
Learn to read from a channel with ChannelReader<T>.
ChannelReader<T>
ChannelReader<T> is the consumer side of a channel. ReadAsync() reads one item asynchronously, waiting if empty and not completed. TryRead(out T item) tries immediately.
ReadAllAsync() returns an IAsyncEnumerable<T>; with await foreach you stream every item until the channel completes. This is the most common consumption pattern.
Consume with await foreach
The pattern await foreach (var item in channel.Reader.ReadAllAsync()) drains every item from the channel in order. When the channel completes (Writer.Complete()), the loop ends gracefully.
This guarantees no item is lost in a producer-consumer pipeline. Inside the loop body you process, filter or collect each item. On an uncompleted channel the loop continues as new items arrive.
Exercise Write and read
channel is an unbounded string channel. Write three items ("a", "b", "c") with await channel.Writer.WriteAsync. Then in a for loop read three times with await channel.Reader.ReadAsync() and print each item. Make Main async Task.
Show example solution
Call await channel.Writer.WriteAsync(...) three times. Then for (int i = 0; i < 3; i++) { var item = await channel.Reader.ReadAsync(); Console.WriteLine(item); }
Example solution:
using System;
using System.Threading.Channels;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
var channel = Channel.CreateUnbounded<string>();
await channel.Writer.WriteAsync("a");
await channel.Writer.WriteAsync("b");
await channel.Writer.WriteAsync("c");
for (int i = 0; i < 3; i++)
{
var item = await channel.Reader.ReadAsync();
Console.WriteLine(item);
}
}
}
Test yourself
-
Complete the ReadAsync call
var item = await channel.Reader.____;
Show answer
var item = await channel.Reader.ReadAsync();
-
Match each read method
- ReadAsync
- Read one item asynchronously
- TryRead
- Try now, return bool
- ReadAllAsync
- Read the whole stream
-
Which method reads all items as a stream from a ChannelReader?
- ReadAll
- ReadAllAsync
- ReadEverything
- ReadStream
Show answer
ReadAllAsync — Correct. ReadAllAsync returns the whole stream.
Next lesson: Bounded channel