A pipeline is a chain of stages joined by channels. Each stage reads from one and writes to the next, and each stage can have its own number of workers. Bounded channels mean a slow stage automatically slows those before it. Getting one right comes down to three questions: who completes each channel, where do errors go, and what happens on cancellation?
A two-stage pipeline
A generic stage helper keeps this short. It takes an input reader, runs a number of workers, and completes its output when they've all finished. Even if a worker fails, the output is completed, with the failure attached.
using System.Threading.Channels;
Channel<string> lines = Channel.CreateBounded<string>(2);
Channel<int> lengths = Channel.CreateBounded<int>(2);
Channel<string> labels = Channel.CreateBounded<string>(2);
Task feed = FeedAsync();
Task first = StageAsync(lines.Reader, lengths.Writer, 2, async line =>
{
await Task.Yield();
return line.Length;
});
Task second = StageAsync(lengths.Reader, labels.Writer, 1, async length =>
{
await Task.Yield();
return length > 3 ? "long" : "short";
});
var counts = new Dictionary<string, int>();
await foreach (string label in labels.Reader.ReadAllAsync())
{
counts[label] = counts.GetValueOrDefault(label) + 1;
}
await Task.WhenAll(feed, first, second);
Console.WriteLine($"long: {counts["long"]}");
Console.WriteLine($"short: {counts["short"]}");
async Task FeedAsync()
{
foreach (string line in new[] { "a", "abcd", "ab", "abcde", "abc" })
{
await lines.Writer.WriteAsync(line);
}
lines.Writer.Complete();
}
static async Task StageAsync<TIn, TOut>(ChannelReader<TIn> input, ChannelWriter<TOut> output, int workers, Func<TIn, Task<TOut>> work)
{
async Task RunAsync()
{
await foreach (TIn item in input.ReadAllAsync())
{
await output.WriteAsync(await work(item));
}
}
try
{
await Task.WhenAll(Enumerable.Range(0, workers).Select(_ => RunAsync()));
output.Complete();
}
catch (Exception e)
{
output.Complete(e);
throw;
}
}Check your prediction
long: 2
short: 3The deadlock to avoid
Here's the classic bug. A producer writes to a bounded channel while the same code plans to read it afterwards. The channel fills, the write waits for a reader, and the reader never starts because it's waiting for the write. This example has a safety timeout, so that it ends instead of hanging.
using System.Threading.Channels;
Channel<int> channel = Channel.CreateBounded<int>(1);
using var safety = new CancellationTokenSource(50);
try
{
await channel.Writer.WriteAsync(1, safety.Token);
Console.WriteLine("first fits");
await channel.Writer.WriteAsync(2, safety.Token);
Console.WriteLine("never reached");
}
catch (OperationCanceledException)
{
Console.WriteLine("stuck: nobody is reading");
}Check your prediction
first fits
stuck: nobody is readingSo start readers before or alongside writers, and don't await a writer before you start reading. In the first example, the final await foreach is what keeps everything moving.
Build it yourself
A log pipeline
Write a pipeline with three stages and bounded channels of capacity 2:
- Parse: read lines from an
IEnumerable<string>, with each line beinglevel message. Lines that don't have both parts are counted as bad and skipped. - Filter: two workers drop any record below the minimum level (
INFOis belowWARN, which is belowERROR). - Collect: the main code gathers the records and counts them per level.
Write it as RunAsync(IEnumerable<string> lines, string minimum, CancellationToken token), returning a record with the counts and the number of bad lines. Print the results for the sample with minimum WARN, in ERROR: 1 format, sorted. Then show the following: a cancelled token leaves no task hanging, with OperationCanceledException reaching the caller; and an input sequence that throws reaches the caller as its own exception.
Get the three stages producing the counts first: that's the core, and it's most of the work. The cancellation and failing-input checks come after, and if you run out of time they make a good start to a second session.
When it works, it prints:
ERROR: 1
WARN: 2
Bad: 1
cancelled
input failedusing System.Threading.Channels;
string[] sample = { "INFO started", "WARN disk low", "bad", "ERROR disk full", "WARN disk low", "INFO stopped" };
await Task.Yield();
Console.WriteLine(sample.Length);Hint 1: the idea
Each stage has one output channel and completes it in a finally or catch, passing on any failure. An error then flows downstream, and the final read throws it. Pass the token to each wait.
Hint 2: a first step
Write the stages with no token and no failure handling, and get the counts right. Then add the failing input, and last the token.
Show one solution
using System.Threading.Channels;
string[] sample = { "INFO started", "WARN disk low", "bad", "ERROR disk full", "WARN disk low", "INFO stopped" };
Summary summary = await LogPipeline.RunAsync(sample, "WARN", CancellationToken.None);
foreach ((string level, int count) in summary.Counts.OrderBy(pair => pair.Key))
{
Console.WriteLine($"{level}: {count}");
}
Console.WriteLine($"Bad: {summary.Bad}");
using (var source = new CancellationTokenSource())
{
source.Cancel();
try
{
await LogPipeline.RunAsync(sample, "WARN", source.Token);
}
catch (OperationCanceledException)
{
Console.WriteLine("cancelled");
}
}
try
{
await LogPipeline.RunAsync(Broken(), "WARN", CancellationToken.None);
}
catch (IOException e)
{
Console.WriteLine(e.Message);
}
static IEnumerable<string> Broken()
{
yield return "WARN first";
throw new IOException("input failed");
}
record Entry(string Level, string Message);
record Summary(Dictionary<string, int> Counts, int Bad);
static class LogPipeline
{
private static readonly string[] Levels = { "INFO", "WARN", "ERROR" };
public static async Task<Summary> RunAsync(IEnumerable<string> lines, string minimum, CancellationToken token)
{
Channel<Entry> parsed = Channel.CreateBounded<Entry>(2);
Channel<Entry> kept = Channel.CreateBounded<Entry>(2);
int bad = 0;
int floor = Array.IndexOf(Levels, minimum);
async Task ParseAsync()
{
try
{
foreach (string line in lines)
{
string[] parts = line.Split(' ', 2);
if (parts.Length != 2 || !Levels.Contains(parts[0]))
{
bad++;
continue;
}
await parsed.Writer.WriteAsync(new Entry(parts[0], parts[1]), token);
}
parsed.Writer.Complete();
}
catch (Exception e)
{
parsed.Writer.Complete(e);
}
}
async Task FilterAsync()
{
await foreach (Entry entry in parsed.Reader.ReadAllAsync(token))
{
if (Array.IndexOf(Levels, entry.Level) >= floor)
{
await kept.Writer.WriteAsync(entry, token);
}
}
}
async Task FiltersAsync()
{
try
{
await Task.WhenAll(FilterAsync(), FilterAsync());
kept.Writer.Complete();
}
catch (Exception e)
{
kept.Writer.Complete(e);
}
}
Task parsing = ParseAsync();
Task filtering = FiltersAsync();
var counts = new Dictionary<string, int>();
await foreach (Entry entry in kept.Reader.ReadAllAsync(CancellationToken.None))
{
counts[entry.Level] = counts.GetValueOrDefault(entry.Level) + 1;
}
await Task.WhenAll(parsing, filtering);
return new Summary(counts, bad);
}
}ERROR: 1
WARN: 2
Bad: 1
cancelled
input failedLook at how cancellation reaches the caller: stages stop waiting, complete their channel with the exception, and the final await foreach rethrows it. Interlocked isn't needed for bad here, since only the single parse stage changes it. Two questions before you move on: what would go wrong if you passed token to the last ReadAllAsync? Would anything be left running?
Completion is saved in this browser only. It does not measure mastery.