Press Run. A healthy result is one line. It takes only a few seconds, mostly compiling, even though the code has retries and timeouts, since the fake delayer doesn't really wait.
Runner checksC##nullable enable
using JobRunner;
int failures = 0;
void Check(bool passed, string name)
{
if (!passed)
{
Console.WriteLine($"FAILED: {name}");
failures++;
}
}
static async Task<List<Outcome>> Collect(Runner runner, IEnumerable<Job> jobs, CancellationToken token = default)
{
var outcomes = new List<Outcome>();
await foreach (Outcome outcome in runner.RunAsync(jobs, token))
{
outcomes.Add(outcome);
}
return outcomes;
}
// A shutdown bug should fail a check, not hang the run.
static async Task<bool> LeftInTime(IAsyncEnumerator<Outcome> stream)
{
Task leaving = stream.DisposeAsync().AsTask();
if (await Task.WhenAny(leaving, Task.Delay(5000)) != leaving)
{
return false;
}
await leaving;
return true;
}
static List<Job> UpperJobs(int count) => Enumerable.Range(1, count).Select(id => (Job)new UpperJob(id, "x")).ToList();
// Parsing
Check(JobParser.Parse("1 sum 1,2,3") is SumJob { Id: 1 }, "parses sum");
Check(JobParser.Parse("2 upper two words") is UpperJob { Text: "two words" }, "keeps spaces in text");
Check(JobParser.Parse("3 flaky 0") is FlakyJob, "accepts zero failures");
Check(JobParser.Parse("4 slow 0") is SlowJob, "accepts a zero delay");
Check(JobParser.Parse("0 upper x") is null, "refuses id 0");
Check(JobParser.Parse("1 sum 1,x") is null, "refuses a bad number");
Check(JobParser.Parse("1 flaky -1") is null, "refuses negative failures");
Check(JobParser.Parse("1 slow -1") is null, "refuses a negative delay");
Check(JobParser.Parse("1 nope x") is null, "refuses an unknown kind");
Check(JobParser.Parse("1 upper") is null, "refuses a missing argument");
// Options
foreach (var bad in new[] { new RunnerOptions { Workers = 0 }, new RunnerOptions { Capacity = 0 }, new RunnerOptions { MaxAttempts = 0 } })
{
try
{
_ = new Runner(new CountingHandler(), new FakeDelayer(), bad);
Check(false, "refuses a bad option");
}
catch (ArgumentOutOfRangeException)
{
}
}
// Every job gets exactly one outcome
var all = await Collect(new Runner(new CountingHandler(), new FakeDelayer(), new RunnerOptions()), UpperJobs(25));
Check(all.Select(o => o.JobId).OrderBy(id => id).SequenceEqual(Enumerable.Range(1, 25)), "one outcome per job");
Check((await Collect(new Runner(new CountingHandler(), new FakeDelayer(), new RunnerOptions()), new List<Job>())).Count == 0, "no jobs gives no outcomes");
// Concurrency stays at the limit, and reaches it
foreach (int workers in new[] { 1, 3 })
{
var counting = new CountingHandler();
await Collect(new Runner(counting, new FakeDelayer(), new RunnerOptions { Workers = workers }), UpperJobs(12));
Check(counting.Peak == workers, $"{workers} workers run at once");
}
// Backpressure: a blocked worker stops the producer pulling more jobs
var gate = new GateHandler();
int pulled = 0;
IEnumerable<Job> Tracked()
{
for (int id = 1; id <= 50; id++)
{
pulled++;
yield return new UpperJob(id, "x");
}
}
Task<List<Outcome>> blocked = Collect(new Runner(gate, new FakeDelayer(), new RunnerOptions { Workers = 1, Capacity = 2 }), Tracked());
await Task.Delay(30);
Check(pulled <= 4, "the bounded queue limits how far the input is read");
gate.Open();
Check((await blocked).Count == 50, "all jobs finish once unblocked");
// Backpressure: a caller holding back an outcome also stops the input being read
int pulledForSlowCaller = 0;
IEnumerable<Job> TrackedForSlowCaller()
{
for (int id = 1; id <= 30; id++)
{
pulledForSlowCaller++;
yield return new UpperJob(id, "x");
}
}
var slowCaller = new Runner(new CountingHandler(), new FakeDelayer(), new RunnerOptions { Workers = 1, Capacity = 2 }).RunAsync(TrackedForSlowCaller()).GetAsyncEnumerator();
await slowCaller.MoveNextAsync();
await Task.Delay(150);
// 1 outcome taken, 2 outcomes buffered, 1 held by the worker, 2 queued, 1 at the producer.
Check(pulledForSlowCaller <= 7, "a slow caller limits how far the input is read");
Check(await LeftInTime(slowCaller), "leaving ends a run with full channels");
// Leaving early stops the input and the work, and waits for them to end
var stoppable = new StoppableHandler();
int pulledBeforeLeaving = 0;
IEnumerable<Job> ManyJobs()
{
for (int id = 1; id <= 1000; id++)
{
pulledBeforeLeaving++;
yield return new UpperJob(id, "x");
}
}
var leaver = new Runner(stoppable, new FakeDelayer(), new RunnerOptions { Workers = 2, Capacity = 2 }).RunAsync(ManyJobs()).GetAsyncEnumerator();
await leaver.MoveNextAsync();
await stoppable.Started.Task;
if (!await LeftInTime(leaver))
{
Check(false, "leaving early ends the run");
}
else
{
Check(stoppable.Running == 0, "leaving early waits for running jobs to end");
Check(stoppable.Stopped >= 1, "leaving early cancels running jobs");
int pulledAtExit = pulledBeforeLeaving;
await Task.Delay(20);
Check(pulledBeforeLeaving == pulledAtExit, "leaving early stops reading the input");
}
// Retries with exponential backoff
var delays = new FakeDelayer();
var retried = await Collect(new Runner(new StandardHandler(delays), delays, new RunnerOptions { MaxAttempts = 4, BaseDelay = TimeSpan.FromMilliseconds(10) }), new Job[] { new FlakyJob(1, 3) });
Check(retried.Single() is Succeeded { Attempts: 4, Output: "recovered" }, "retries until success");
Check(delays.Requested.Select(d => (int)d.TotalMilliseconds).SequenceEqual(new[] { 10, 20, 40 }), "delays double");
var givenUp = await Collect(new Runner(new StandardHandler(delays), delays, new RunnerOptions { MaxAttempts = 2 }), new Job[] { new FlakyJob(1, 5) });
Check(givenUp.Single() is Failed { Attempts: 2 }, "gives up at the attempt limit");
var once = await Collect(new Runner(new StandardHandler(delays), delays, new RunnerOptions { MaxAttempts = 1 }), new Job[] { new FlakyJob(1, 1) });
Check(once.Single() is Failed { Attempts: 1 }, "one attempt means no retry");
var permanent = new ThrowingHandler();
var notRetried = await Collect(new Runner(permanent, delays, new RunnerOptions()), new Job[] { new UpperJob(1, "x") });
Check(notRetried.Single() is Failed { Attempts: 1, Reason: "broken" } && permanent.Calls == 1, "an ordinary exception is not retried");
// A timeout ends one job without stopping the rest
var real = new RealDelayer();
var timed = await Collect(new Runner(new StandardHandler(real), real, new RunnerOptions { Timeout = TimeSpan.FromMilliseconds(20) }), new Job[] { new SlowJob(1, 5000), new UpperJob(2, "x") });
Check(timed.Single(o => o.JobId == 1) is TimedOut { Attempts: 1 }, "a slow job times out");
Check(timed.Single(o => o.JobId == 2) is Succeeded, "other jobs still run");
// Cancelling reports every job, and starts no new work
using (var source = new CancellationTokenSource())
{
var cancellable = new CountingHandler { CancelAfterFirst = source };
var cancelled = await Collect(new Runner(cancellable, new FakeDelayer(), new RunnerOptions { Workers = 1 }), UpperJobs(10), source.Token);
Check(cancelled.Count == 10, "cancelling still reports every job");
Check(cancelled.OfType<Cancelled>().Count() == 9, "unstarted jobs are cancelled");
Check(cancelled.OfType<Cancelled>().All(outcome => outcome.Attempts == 0), "a cancelled job that never started used no attempts");
Check(cancellable.Calls == 1, "no job starts after cancellation");
}
using (var source = new CancellationTokenSource())
{
source.CancelAfter(20);
var inFlight = await Collect(new Runner(new StandardHandler(real), real, new RunnerOptions()), new Job[] { new SlowJob(1, 5000) }, source.Token);
Check(inFlight.Single() is Cancelled { Attempts: 1 }, "a running job sees cancellation");
}
using (var source = new CancellationTokenSource())
{
source.CancelAfter(20);
long started = Environment.TickCount64;
var backingOff = await Collect(new Runner(new StandardHandler(real), real, new RunnerOptions { BaseDelay = TimeSpan.FromSeconds(2) }), new Job[] { new FlakyJob(1, 1) }, source.Token);
Check(backingOff.Single() is Cancelled { Attempts: 1 }, "a job cancelled during backoff reports its attempt");
Check(Environment.TickCount64 - started < 1000, "cancelling interrupts a backoff delay");
}
// A failing input reaches the caller rather than hanging
IEnumerable<Job> Broken()
{
yield return new UpperJob(1, "x");
throw new InvalidOperationException("bad input");
}
try
{
await Collect(new Runner(new CountingHandler(), new FakeDelayer(), new RunnerOptions()), Broken());
Check(false, "an input failure is reported");
}
catch (InvalidOperationException)
{
}
if (failures > 0)
{
Console.WriteLine($"{failures} checks failed");
return 1;
}
Console.WriteLine("Runner checks passed");
return 0;
class FakeDelayer : IDelayer
{
public List<TimeSpan> Requested { get; } = new();
public Task DelayAsync(TimeSpan duration, CancellationToken token)
{
Requested.Add(duration);
return Task.CompletedTask;
}
}
class CountingHandler : IJobHandler
{
private readonly object peakLock = new();
private int running;
private int calls;
public int Peak { get; private set; }
public int Calls => calls;
public CancellationTokenSource? CancelAfterFirst { get; init; }
public async ValueTask<string> HandleAsync(Job job, int attempt, CancellationToken token)
{
Interlocked.Increment(ref calls);
int now = Interlocked.Increment(ref running);
lock (peakLock)
{
Peak = Math.Max(Peak, now);
}
await Task.Delay(1, CancellationToken.None);
Interlocked.Decrement(ref running);
CancelAfterFirst?.Cancel();
return "ok";
}
}
class GateHandler : IJobHandler
{
private readonly TaskCompletionSource gate = new(TaskCreationOptions.RunContinuationsAsynchronously);
public void Open() => gate.SetResult();
public async ValueTask<string> HandleAsync(Job job, int attempt, CancellationToken token)
{
await gate.Task;
return "ok";
}
}
// The first job finishes at once; later jobs run until cancelled, then take time to clean up.
class StoppableHandler : IJobHandler
{
private int running;
private int stopped;
public TaskCompletionSource Started { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public int Running => Volatile.Read(ref running);
public int Stopped => Volatile.Read(ref stopped);
public async ValueTask<string> HandleAsync(Job job, int attempt, CancellationToken token)
{
if (job.Id == 1)
{
return "ok";
}
Interlocked.Increment(ref running);
Started.TrySetResult();
try
{
await Task.Delay(Timeout.Infinite, token);
return "never";
}
catch (OperationCanceledException)
{
await Task.Delay(5, CancellationToken.None);
Interlocked.Increment(ref stopped);
throw;
}
finally
{
Interlocked.Decrement(ref running);
}
}
}
class ThrowingHandler : IJobHandler
{
public int Calls { get; private set; }
public ValueTask<string> HandleAsync(Job job, int attempt, CancellationToken token)
{
Calls++;
throw new InvalidOperationException("broken");
}
}
#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);
}
}
How each invariant is proved
One outcome per job. 25 jobs go in, and the ids that come out are compared, sorted, with 1 to 25. Duplicates or gaps both fail.
The concurrency limit.CountingHandler records the peak running at once. The check requires it to equal the worker count: going over is a bug, and so is never reaching it.
Backpressure.GateHandler holds a single worker, the input is a lazy sequence that counts each item pulled, and the check confirms that only a few were pulled. It's the Day 4 experiment made into a test. A second check holds back the caller instead: it reads one outcome and stops, and the input may only be read as far as the buffers and in-flight work allow.
Leaving early. A caller that disposes the stream after one outcome must end the run. The check waits for disposal behind a five-second limit, so a shutdown bug fails rather than hangs, then confirms that running jobs were cancelled and finished, and that the input stopped being read.
Failing input. An input that throws must surface at the caller. If it hangs instead, the whole run hangs, and the project's own automated tests have a timeout that catches that.
Break it on purpose
Make one change at a time in the tabs above, and confirm that a check fails. Then undo it.
File
Change
What should fail
Runner.cs
Channel.CreateBounded<Job>(options.Capacity) to Channel.CreateUnbounded<Job>()
The bounded queue limit
Runner.cs
Channel.CreateBounded<Outcome>(options.Capacity) to Channel.CreateUnbounded<Outcome>()
A slow caller limits the input
Runner.cs
Remove leaving.Cancel();
Leaving ends a run with full channels
Runner.cs
attempt >= options.MaxAttempts to >
Attempt limits
Runner.cs
Math.Pow(2, attempt - 1) to attempt
Delays double
Runner.cs
Remove timeout.CancelAfter(options.Timeout);
A slow job times out
Jobs.cs
id < 1 to id < 0
Refuses id 0
The project's automated tests apply 19 such changes on each run. One of them found a real weakness while this course was being written: nothing noticed if cancelling failed to interrupt a backoff delay, because the job still reported the right outcome, only much later. That's why there's a check on elapsed time, with a generous limit.
An honest timing check
A test about time needs some real time, and that's where flakiness creeps in. Use a limit far from the expected value, so only a real failure can cross it. Here the work should end almost at once, and the limit is a full second.
A generous boundC#
using var source = new CancellationTokenSource(10);
long started = Environment.TickCount64;
try
{
await Task.Delay(TimeSpan.FromSeconds(30), source.Token);
}
catch (OperationCanceledException)
{
Console.WriteLine("interrupted");
}
Console.WriteLine(Environment.TickCount64 - started < 1000);
Check your prediction
Text
interruptedTrue
Fakes record what happened
FakeDelayer returns immediately and remembers each duration. It makes the "delays double" check exact, a thing no real clock could do. Predict the recorded list.
Exact delays, no waitingC#
var delays = new FakeDelayer();
TimeSpan baseDelay = TimeSpan.FromMilliseconds(10);
for (int attempt = 1; attempt <= 3; attempt++)
{
await delays.DelayAsync(baseDelay * Math.Pow(2, attempt - 1));
}
Console.WriteLine(string.Join(",", delays.Requested.Select(delay => (int)delay.TotalMilliseconds)));
class FakeDelayer
{
public List<TimeSpan> Requested { get; } = new();
public Task DelayAsync(TimeSpan duration)
{
Requested.Add(duration);
return Task.CompletedTask;
}
}
Check your prediction
Text
10,20,40
Your turn
Exercise
Check cancellation against the handler's record
The checks above count outcomes after a cancellation. They don't compare what the runner reports with what the handler saw, and that comparison is the strongest form of "one outcome per job". Write a new check for the runner, in the workspace below:
A RecordingHandler remembers the id of every job it's called with, and cancels a CancellationTokenSource on its fifth call.
Run 20 UpperJobs with 3 workers and that token, and collect every outcome behind a WaitAsync(TimeSpan.FromSeconds(5)).
Check that the ids 1 to 20 each appear exactly once; that at least one job was cancelled with 0 attempts (otherwise the test never exercised cancellation); that a job has attempts exactly when the handler was called for it; and that a job with 0 attempts is Cancelled.
Print Cancellation checks passed if all is well, and return 1 otherwise:
Text
Cancellation checks passed
Then test your check. In the Runner.cs tab, change new Cancelled(job.Id, attempt - 1) to new Cancelled(job.Id, attempt) and run it: the "attempts exactly when its handler ran" check should be among the failures. Undo that, change if (token.IsCancellationRequested) to if (false), and see which check fails now. Undo it again.
Your workspaceC##nullable enable
using JobRunner;
var jobs = Enumerable.Range(1, 3).Select(id => (Job)new UpperJob(id, "x"));
var runner = new Runner(new StandardHandler(new RealDelayer()), new RealDelayer(), new RunnerOptions());
await foreach (Outcome outcome in runner.RunAsync(jobs))
{
Console.WriteLine(outcome);
}
#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);
}
}
Hint 1: the idea
The handler is the witness. It records every job that reached it, and the runner reports an attempt count for every job. Those two records must agree: attempts above 0 means the handler ran, and 0 means it didn't. Cancelling from inside the handler makes the moment of cancellation exact, with no timing involved.
Hint 2: a first step
Write RecordingHandler with a HashSet<int> behind a lock (handlers can run at the same time on real threads), call Cancel() when the set reaches five ids, and print each outcome. You should see a few Succeeded lines followed by Cancelled lines with Attempts = 0.
Show one solution
C#
// With the job runner's library: Runner.cs, Handlers.cs and Jobs.cs#nullable enableusing JobRunner;int failures = 0;void Check(bool passed, string name){ if (!passed) { Console.WriteLine($"FAILED: {name}"); failures++; }}using var source = new CancellationTokenSource();var handler = new RecordingHandler(source, cancelOnCall: 5);var runner = new Runner(handler, new FakeDelayer(), new RunnerOptions { Workers = 3 });var jobs = Enumerable.Range(1, 20).Select(id => (Job)new UpperJob(id, "x"));List<Outcome> outcomes = await Collect(runner, jobs, source.Token).WaitAsync(TimeSpan.FromSeconds(5));Check(outcomes.Select(outcome => outcome.JobId).Order().SequenceEqual(Enumerable.Range(1, 20)), "every job has exactly one outcome");Check(outcomes.OfType<Cancelled>().Any(outcome => outcome.Attempts == 0), "the run really was cancelled midway");Check(outcomes.All(outcome => (outcome.Attempts > 0) == handler.Called(outcome.JobId)), "a job has attempts exactly when its handler ran");Check(outcomes.Where(outcome => outcome.Attempts == 0).All(outcome => outcome is Cancelled), "a job with no attempts is cancelled");if (failures > 0){ return 1;}Console.WriteLine("Cancellation checks passed");return 0;static async Task<List<Outcome>> Collect(Runner runner, IEnumerable<Job> jobs, CancellationToken token){ var outcomes = new List<Outcome>(); await foreach (Outcome outcome in runner.RunAsync(jobs, token)) { outcomes.Add(outcome); } return outcomes;}class FakeDelayer : IDelayer{ public Task DelayAsync(TimeSpan duration, CancellationToken token) => Task.CompletedTask;}// Records which jobs reached the handler, and cancels the run on a chosen call.class RecordingHandler(CancellationTokenSource source, int cancelOnCall) : IJobHandler{ private readonly HashSet<int> called = new(); public bool Called(int id) { lock (called) { return called.Contains(id); } } public async ValueTask<string> HandleAsync(Job job, int attempt, CancellationToken token) { int calls; lock (called) { called.Add(job.Id); calls = called.Count; } if (calls == cancelOnCall) { source.Cancel(); } await Task.Yield(); return "ok"; }}
Text
Cancellation checks passed
The second check is the one people forget. Without it, a runner that ignored cancellation completely would pass: every job would succeed, so the other three checks would hold without testing anything. The mutation if (false) shows exactly that, and only that check fails. The handler's own FakeDelayer and await Task.Yield() keep the run instant, and cancelling on the fifth call rather than after a delay means the test checks the same properties on one thread or many. It passes on the .NET 10 SDK with real threads as well as here.
Completion is saved in this browser only. It does not measure mastery.