Concurrent programs fail mostly at shared state: two tasks changing one thing. A channel avoids that. It's a thread-safe queue for handing items from producers to consumers. Only one task owns an item at a time, so there's nothing to lock. The motto is "share by communicating".
Writer and reader
Channel.CreateUnbounded<T> gives a channel with no size limit. Its two sides are separate properties: Writer and Reader. Complete says that nothing more is coming, and ReadAllAsync loops until the channel is both complete and empty. Forgetting Complete leaves the reader waiting forever.
using System.Threading.Channels;
Channel<int> channel = Channel.CreateUnbounded<int>();
Task producer = ProduceAsync(channel.Writer);
await foreach (int value in channel.Reader.ReadAllAsync())
{
Console.WriteLine(value);
}
await producer;
Console.WriteLine("done");
static async Task ProduceAsync(ChannelWriter<int> writer)
{
for (int i = 1; i <= 3; i++)
{
await writer.WriteAsync(i * 10);
}
writer.Complete();
}Check your prediction
10
20
30
donePass code only the half it needs. A method taking ChannelWriter<int> can't read from the channel, and the signature documents its role.
Several consumers
Start more than one reader, and each item goes to exactly one. That's a worker pool. Items are shared out automatically, and a slow worker just takes fewer. Results may finish out of order, so this example sorts them. Outcomes go to a second channel, which keeps workers free of any shared list.
using System.Threading.Channels;
Channel<int> jobs = Channel.CreateUnbounded<int>();
Channel<string> results = Channel.CreateUnbounded<string>();
for (int i = 1; i <= 6; i++)
{
await jobs.Writer.WriteAsync(i);
}
jobs.Writer.Complete();
Task[] workers = Enumerable.Range(1, 3).Select(WorkAsync).ToArray();
await Task.WhenAll(workers);
results.Writer.Complete();
var all = new List<string>();
await foreach (string result in results.Reader.ReadAllAsync())
{
all.Add(result);
}
Console.WriteLine(string.Join(",", all.Order()));
async Task WorkAsync(int worker)
{
await foreach (int job in jobs.Reader.ReadAllAsync())
{
await Task.Delay(1);
await results.Writer.WriteAsync($"job{job}");
}
}Check your prediction
job1,job2,job3,job4,job5,job6On your computer, these workers really can run on separate threads. Channels remain correct there, and a plain List<string> wouldn't be. That's the portability you get from this design.
Errors
Complete can carry an exception: after the remaining items are read, the reader throws it. That's how a failing producer tells its consumers, rather than leaving them hanging. TryWrite and TryRead are the versions that don't wait, and they return false when they can't proceed.
using System.Threading.Channels;
Channel<int> channel = Channel.CreateUnbounded<int>();
Console.WriteLine(channel.Writer.TryWrite(1));
channel.Writer.Complete(new InvalidOperationException("source failed"));
Console.WriteLine(channel.Writer.TryWrite(2));
try
{
await foreach (int value in channel.Reader.ReadAllAsync())
{
Console.WriteLine(value);
}
}
catch (InvalidOperationException e)
{
Console.WriteLine(e.Message);
}Check your prediction
True
False
1
source failedWho completes what?
Here's the rule that prevents most hangs: whoever writes, completes. With one producer, it completes when it's finished. With several writers, none can complete alone, so one coordinating task awaits them all and then completes the channel. The finally below makes sure that happens even after a failure.
using System.Threading.Channels;
Channel<string> channel = Channel.CreateUnbounded<string>();
Task coordinator = CoordinateAsync();
var seen = new List<string>();
await foreach (string item in channel.Reader.ReadAllAsync())
{
seen.Add(item);
}
await coordinator;
Console.WriteLine(string.Join(",", seen.Order()));
async Task CoordinateAsync()
{
try
{
await Task.WhenAll(WriteAsync("a"), WriteAsync("b"));
}
finally
{
channel.Writer.Complete();
}
}
async Task WriteAsync(string prefix)
{
for (int i = 1; i <= 2; i++)
{
await Task.Delay(1);
await channel.Writer.WriteAsync($"{prefix}{i}");
}
}Check your prediction
a1,a2,b1,b2Your turn
Word counts by worker pool
Write CountWordsAsync(IEnumerable<string> lines, int workers), which returns a Dictionary<string, int> of word counts. The lines go into one channel, each of the workers counts one line into its own small dictionary and writes that to a results channel, and a single reader merges the results. No two tasks should touch the same dictionary.
Print the counts for the cat, the dog and a cat with 3 workers, sorted by word, in the form a=1. Then show that one worker gives the same result, and that empty input gives an empty dictionary.
When it works, it prints:
a=1 cat=2 dog=1 the=2
a=1 cat=2 dog=1 the=2
0using System.Threading.Channels;
string[] lines = { "the cat", "the dog", "a cat" };
await Task.Yield();
Console.WriteLine(lines.Length);Hint 1: the idea
There are three stages: feed lines, workers turn lines into small dictionaries, and one merger reads them. Only the merger owns the final dictionary.
Hint 2: a first step
Remember who completes what: the feeder completes the lines channel, and the results channel completes after every worker has finished. Sort with OrderBy on the key when you print.
Show one solution
using System.Threading.Channels;
string[] lines = { "the cat", "the dog", "a cat" };
Print(await CountWordsAsync(lines, 3));
Print(await CountWordsAsync(lines, 1));
Console.WriteLine((await CountWordsAsync(Array.Empty<string>(), 2)).Count);
static void Print(Dictionary<string, int> counts)
{
Console.WriteLine(string.Join(" ", counts.OrderBy(pair => pair.Key).Select(pair => $"{pair.Key}={pair.Value}")));
}
static async Task<Dictionary<string, int>> CountWordsAsync(IEnumerable<string> lines, int workers)
{
Channel<string> input = Channel.CreateUnbounded<string>();
Channel<Dictionary<string, int>> output = Channel.CreateUnbounded<Dictionary<string, int>>();
foreach (string line in lines)
{
input.Writer.TryWrite(line);
}
input.Writer.Complete();
async Task WorkAsync()
{
await foreach (string line in input.Reader.ReadAllAsync())
{
var counts = new Dictionary<string, int>();
foreach (string word in line.Split(' ', StringSplitOptions.RemoveEmptyEntries))
{
counts[word] = counts.GetValueOrDefault(word) + 1;
}
await output.Writer.WriteAsync(counts);
}
}
async Task CoordinateAsync()
{
try
{
await Task.WhenAll(Enumerable.Range(0, workers).Select(_ => WorkAsync()));
}
finally
{
output.Writer.Complete();
}
}
Task coordinator = CoordinateAsync();
var total = new Dictionary<string, int>();
await foreach (Dictionary<string, int> counts in output.Reader.ReadAllAsync())
{
foreach ((string word, int count) in counts)
{
total[word] = total.GetValueOrDefault(word) + count;
}
}
await coordinator;
return total;
}a=1 cat=2 dog=1 the=2
a=1 cat=2 dog=1 the=2
0The input is written and completed up front, so the workers simply drain it. The output has several writers, so it follows the rule from earlier in the lesson: a coordinator awaits every worker and completes the channel in a finally. If a worker fails, the channel is still completed, the reader's loop ends, and await coordinator rethrows the failure.
Completion is saved in this browser only. It does not measure mastery.