Here's the complete program. Read Program.cs first, then Runner.cs, which is the heart of it. Press Run, and compare the output with the brief.
Job runnerC##nullable enable
using JobRunner;
var jobs = new List<Job>();
int rejected = 0;
string? line;
while ((line = Console.ReadLine()) is not null)
{
Job? job = JobParser.Parse(line);
if (job is null || jobs.Any(existing => existing.Id == job.Id))
{
rejected++;
continue;
}
jobs.Add(job);
}
var delayer = new RealDelayer();
var options = new RunnerOptions { Timeout = TimeSpan.FromMilliseconds(200) };
var runner = new Runner(new StandardHandler(delayer), delayer, options);
var outcomes = new List<Outcome>();
await foreach (Outcome outcome in runner.RunAsync(jobs))
{
outcomes.Add(outcome);
}
// Outcomes arrive in finishing order, which varies, so sort them for a stable report.
foreach (Outcome outcome in outcomes.OrderBy(outcome => outcome.JobId))
{
Console.WriteLine(outcome switch
{
Succeeded s => $"Job {s.JobId}: {s.Output} (attempts: {s.Attempts})",
Failed f => $"Job {f.JobId}: failed, {f.Reason} (attempts: {f.Attempts})",
TimedOut t => $"Job {t.JobId}: timed out (attempts: {t.Attempts})",
Cancelled c => $"Job {c.JobId}: cancelled (attempts: {c.Attempts})",
_ => throw new InvalidOperationException("unknown outcome"),
});
}
Console.WriteLine($"Succeeded: {outcomes.OfType<Succeeded>().Count()}");
Console.WriteLine($"Failed: {outcomes.OfType<Failed>().Count()}");
Console.WriteLine($"Timed out: {outcomes.OfType<TimedOut>().Count()}");
Console.WriteLine($"Rejected: {rejected}");
#nullable enable
using System.Runtime.CompilerServices;
using System.Threading.Channels;
namespace JobRunner;
public sealed record RunnerOptions
{
public int Workers { get; init; } = 2;
public int Capacity { get; init; } = 4;
public int MaxAttempts { get; init; } = 3;
public TimeSpan BaseDelay { get; init; } = TimeSpan.FromMilliseconds(10);
public TimeSpan Timeout { get; init; } = TimeSpan.FromSeconds(5);
}
public sealed class Runner
{
private readonly IJobHandler handler;
private readonly IDelayer delayer;
private readonly RunnerOptions options;
public Runner(IJobHandler handler, IDelayer delayer, RunnerOptions options)
{
ArgumentOutOfRangeException.ThrowIfLessThan(options.Workers, 1);
ArgumentOutOfRangeException.ThrowIfLessThan(options.Capacity, 1);
ArgumentOutOfRangeException.ThrowIfLessThan(options.MaxAttempts, 1);
this.handler = handler;
this.delayer = delayer;
this.options = options;
}
// Yields one outcome per job as each finishes, even when the run is cancelled, for as
// long as the caller keeps reading. Leaving early stops the run: remaining jobs get no
// outcome, and disposal waits for the work to end, so a handler must honour its token.
// A caller holding back an outcome limits the input read to Capacity in each channel,
// one job per worker, one waiting at the producer, and the outcomes already taken.
public async IAsyncEnumerable<Outcome> RunAsync(IEnumerable<Job> jobs, [EnumeratorCancellation] CancellationToken token = default)
{
Channel<Job> queue = Channel.CreateBounded<Job>(options.Capacity);
Channel<Outcome> outcomes = Channel.CreateBounded<Outcome>(options.Capacity);
// Cancelling asks for outcomes, so the channels keep moving. Leaving means nobody
// will read them, so anything waiting on a channel must stop waiting too.
using var leaving = new CancellationTokenSource();
using var stopping = CancellationTokenSource.CreateLinkedTokenSource(token, leaving.Token);
Task producer = ProduceAsync(jobs, queue.Writer, leaving.Token);
Task[] workers = Enumerable.Range(0, options.Workers)
.Select(_ => WorkAsync(queue.Reader, outcomes.Writer, stopping.Token, leaving.Token))
.ToArray();
Task finished = FinishAsync(workers.Append(producer), outcomes.Writer);
try
{
await foreach (Outcome outcome in outcomes.Reader.ReadAllAsync(CancellationToken.None))
{
yield return outcome;
}
}
finally
{
leaving.Cancel();
await finished;
}
}
// Waits for room in the bounded queue, so a large input can't outrun the workers.
private static async Task ProduceAsync(IEnumerable<Job> jobs, ChannelWriter<Job> writer, CancellationToken leaving)
{
try
{
foreach (Job job in jobs)
{
await writer.WriteAsync(job, leaving);
}
writer.Complete();
}
catch (Exception e)
{
writer.Complete(e);
throw;
}
}
private async Task WorkAsync(ChannelReader<Job> reader, ChannelWriter<Outcome> writer, CancellationToken stopping, CancellationToken leaving)
{
await foreach (Job job in reader.ReadAllAsync(leaving))
{
await writer.WriteAsync(await RunJobAsync(job, stopping), leaving);
}
}
private async Task<Outcome> RunJobAsync(Job job, CancellationToken token)
{
for (int attempt = 1; ; attempt++)
{
if (token.IsCancellationRequested)
{
return new Cancelled(job.Id, attempt - 1);
}
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(token);
timeout.CancelAfter(options.Timeout);
try
{
string output = await handler.HandleAsync(job, attempt, timeout.Token);
return new Succeeded(job.Id, attempt, output);
}
catch (OperationCanceledException) when (token.IsCancellationRequested)
{
return new Cancelled(job.Id, attempt);
}
catch (OperationCanceledException) when (timeout.IsCancellationRequested)
{
return new TimedOut(job.Id, attempt);
}
catch (TransientException e)
{
if (attempt >= options.MaxAttempts)
{
return new Failed(job.Id, attempt, e.Message);
}
}
catch (Exception e)
{
return new Failed(job.Id, attempt, e.Message);
}
try
{
await delayer.DelayAsync(options.BaseDelay * Math.Pow(2, attempt - 1), token);
}
catch (OperationCanceledException)
{
return new Cancelled(job.Id, attempt);
}
}
}
private static async Task FinishAsync(IEnumerable<Task> tasks, ChannelWriter<Outcome> writer)
{
try
{
await Task.WhenAll(tasks);
writer.Complete();
}
catch (Exception e)
{
writer.Complete(e);
}
}
}
#nullable enable
using System.Diagnostics;
namespace JobRunner;
public interface IDelayer
{
Task DelayAsync(TimeSpan duration, CancellationToken token);
}
public sealed class RealDelayer : IDelayer
{
public Task DelayAsync(TimeSpan duration, CancellationToken token) => Task.Delay(duration, token);
}
public interface IJobHandler
{
ValueTask<string> HandleAsync(Job job, int attempt, CancellationToken token);
}
public sealed class StandardHandler(IDelayer delayer) : IJobHandler
{
public async ValueTask<string> HandleAsync(Job job, int attempt, CancellationToken token)
{
switch (job)
{
case SumJob sum:
return sum.Values.Sum().ToString();
case UpperJob upper:
return upper.Text.ToUpperInvariant();
case FlakyJob flaky when attempt <= flaky.FailuresFirst:
throw new TransientException($"attempt {attempt} failed");
case FlakyJob:
return "recovered";
case SlowJob slow:
await delayer.DelayAsync(TimeSpan.FromMilliseconds(slow.Milliseconds), token);
return "finished";
default:
throw new UnreachableException($"unknown job {job.GetType().Name}");
}
}
}
#nullable enable
namespace JobRunner;
public abstract record Job(int Id);
public sealed record SumJob(int Id, IReadOnlyList<int> Values) : Job(Id);
public sealed record UpperJob(int Id, string Text) : Job(Id);
public sealed record FlakyJob(int Id, int FailuresFirst) : Job(Id);
public sealed record SlowJob(int Id, int Milliseconds) : Job(Id);
// Every job ends in exactly one of these.
public abstract record Outcome(int JobId, int Attempts);
public sealed record Succeeded(int JobId, int Attempts, string Output) : Outcome(JobId, Attempts);
public sealed record Failed(int JobId, int Attempts, string Reason) : Outcome(JobId, Attempts);
public sealed record TimedOut(int JobId, int Attempts) : Outcome(JobId, Attempts);
public sealed record Cancelled(int JobId, int Attempts) : Outcome(JobId, Attempts);
// Thrown by a handler when trying the same job again might work.
public class TransientException : Exception
{
public TransientException(string message) : base(message) { }
}
public static class JobParser
{
public static Job? Parse(string line)
{
string[] parts = line.Split(' ', 3, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length != 3 || !int.TryParse(parts[0], out int id) || id < 1)
{
return null;
}
return parts[1] switch
{
"sum" => ParseSum(id, parts[2]),
"upper" => new UpperJob(id, parts[2]),
"flaky" when int.TryParse(parts[2], out int failures) && failures >= 0 => new FlakyJob(id, failures),
"slow" when int.TryParse(parts[2], out int ms) && ms >= 0 => new SlowJob(id, ms),
_ => null,
};
}
private static SumJob? ParseSum(int id, string text)
{
var values = new List<int>();
foreach (string piece in text.Split(','))
{
if (!int.TryParse(piece, out int value))
{
return null;
}
values.Add(value);
}
return new SumJob(id, values);
}
}
1 sum 1,2,3
2 upper hello world
3 flaky 2
4 flaky 9
5 slow 5000
6 nope x
7 slow 20
1 upper duplicate
Change the input and run it again. Try flaky 3 and flaky 2, a slow above and below 200, and a long list of upper jobs. In this browser, workers take turns on one thread. On your own computer, the same code runs on the thread pool, and it stays correct because the workers share only channels.
Follow one job
Here's what happens to 3 flaky 2.
Program.cs parses it with JobParser, and passes the list to RunAsync.
ProduceAsync writes it to the bounded queue, and waits if the queue is full.
A worker in WorkAsync reads it, and calls RunJobAsync.
RunJobAsync creates a linked token with a timeout, and calls the handler. It throws TransientException, so the backoff delay runs, using RunnerOptions.BaseDelay.
Attempt 3 succeeds. The worker writes a Succeeded to the outcome channel.
RunAsync yields it to Program.cs, which stores it and reports at the end, sorted by id.
Five decisions to notice
The worker's read ignores the caller's token. It uses reader.ReadAllAsync(leaving), not token, which looks wrong at first sight. It's deliberate: on cancellation, workers must drain the queue so that each job gets a Cancelled outcome. If they stopped reading, jobs would vanish, and the producer would wait forever.
The producer ignores the caller's token as well, and for the same reason. Each job must reach a worker, so that it can be reported. It also means a huge input is still walked after a cancel, a real trade-off, and one that you might choose differently.
Cancelling and leaving are different. After a cancel, the caller is still reading and wants an outcome for every job. If the caller disposes the stream early, nobody is reading, and a worker waiting to write to the full outcome channel would wait forever. So the iterator's finally cancels leaving, which releases every channel wait, and then awaits finished, so no work outlives the stream. A bounded outcome channel makes this necessary, and it's what carries backpressure from the caller to the input.
FinishAsync is the coordinator. No worker can complete the outcome channel, since others may still be writing. It awaits them all, and it completes the channel with any exception. So a failing input stream reaches the caller through the outcomes.
Order of catch clauses is the logic. Caller cancellation, then timeout, then transient, then everything else. Both of the first two arrive as OperationCanceledException, and only the when filters tell them apart.
Practice the core idea
Why does draining matter? Compare workers that stop when cancelled with workers that drain. Predict how many outcomes each one reports for 5 jobs.
Stop reading, or drain?C#
using System.Threading.Channels;
Console.WriteLine(await RunAsync(drain: false));
Console.WriteLine(await RunAsync(drain: true));
static async Task<int> RunAsync(bool drain)
{
Channel<int> queue = Channel.CreateUnbounded<int>();
for (int job = 1; job <= 5; job++)
{
queue.Writer.TryWrite(job);
}
queue.Writer.Complete();
using var source = new CancellationTokenSource();
source.Cancel();
int outcomes = 0;
try
{
await foreach (int job in queue.Reader.ReadAllAsync(drain ? CancellationToken.None : source.Token))
{
outcomes++;
}
}
catch (OperationCanceledException)
{
}
return outcomes;
}
Check your prediction
Text
05
Your turn
Exercise
Summarize outcomes
Program.cs prints a line per outcome, plus counts. Write Summarize(IEnumerable<Outcome> outcomes) returning a record Stats(int Succeeded, int Failed, int TimedOut, int Cancelled, int TotalAttempts, double RetriesPerJob), where RetriesPerJob is the number of attempts beyond each job's first, divided by the number of jobs that started at all. Handle no jobs by giving 0.
Using the hierarchy in the workspace, print the stats for a succeeded job on attempt 3, a failed job after 3 attempts, a timed-out job on 1, a cancelled one with 0, then for no outcomes at all.
When it works, it prints the lines below. Each Name { … } line is a record's built-in ToString, so print the record itself rather than formatting it:
var outcomes = new Outcome[] { new Succeeded(1, 3), new Failed(2, 3), new TimedOut(3, 1), new Cancelled(4, 0) };
Console.WriteLine(outcomes.Length);
abstract record Outcome(int JobId, int Attempts);
sealed record Succeeded(int JobId, int Attempts) : Outcome(JobId, Attempts);
sealed record Failed(int JobId, int Attempts) : Outcome(JobId, Attempts);
sealed record TimedOut(int JobId, int Attempts) : Outcome(JobId, Attempts);
sealed record Cancelled(int JobId, int Attempts) : Outcome(JobId, Attempts);
Hint 1: the idea
OfType<T> counts each case. Retries come from the outcomes with at least one attempt, and each of those contributes Attempts - 1.
Hint 2: a first step
Materialize the sequence with ToList so that you only walk it once. Check for a count of 0 before you divide.
Show one solution
C#
var outcomes = new Outcome[] { new Succeeded(1, 3), new Failed(2, 3), new TimedOut(3, 1), new Cancelled(4, 0) };Console.WriteLine(Summarize(outcomes));Console.WriteLine(Summarize(Array.Empty<Outcome>()));static Stats Summarize(IEnumerable<Outcome> outcomes){ List<Outcome> all = outcomes.ToList(); List<Outcome> started = all.Where(outcome => outcome.Attempts > 0).ToList(); double retries = started.Count == 0 ? 0 : started.Sum(outcome => outcome.Attempts - 1) / (double)started.Count; return new Stats( all.OfType<Succeeded>().Count(), all.OfType<Failed>().Count(), all.OfType<TimedOut>().Count(), all.OfType<Cancelled>().Count(), all.Sum(outcome => outcome.Attempts), retries);}record Stats(int Succeeded, int Failed, int TimedOut, int Cancelled, int TotalAttempts, double RetriesPerJob);abstract record Outcome(int JobId, int Attempts);sealed record Succeeded(int JobId, int Attempts) : Outcome(JobId, Attempts);sealed record Failed(int JobId, int Attempts) : Outcome(JobId, Attempts);sealed record TimedOut(int JobId, int Attempts) : Outcome(JobId, Attempts);sealed record Cancelled(int JobId, int Attempts) : Outcome(JobId, Attempts);