Now change the runner yourself. A new job kind shows how far a change spreads, which is a good measure of a design. In this one, it's two small edits, and Runner.cs needs none at all.
A warm-up on outcomes
Before you add a kind, think about what Runner does with whatever a handler throws or returns. Predict these three outcomes from a tiny version of the attempt logic.
A handler that throws an ordinary exception is contained. It can't bring down the worker, or lose the job.
Your turn
Exercise
Add a word-count job
In the tabs below, add a job kind count <text> that returns the number of words, with 3 count two words producing Job 3: 2 (attempts: 1). Add a line to the input box, and press Run. You should only need Jobs.cs and Handlers.cs. Then add a check for it in Checks.cs.
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:
Text
CountJob { Id = 3, Text = two words }2
Your workspaceC##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
Hint 1: the idea
There are three parts: a new record derived from Job, one arm in the parser's switch, and one case in StandardHandler.
Hint 2: a first step
Declare sealed record CountJob(int Id, string Text) : Job(Id);, then add the parser arm. Without a handler case, the job fails with unknown job CountJob, so the default branch does its job.
Show one solution
The changed parts are put together in one file, so that this listing can run by itself.
C#
#nullable enableusing System.Diagnostics;Job? job = Parse("3 count two words");Console.WriteLine(job);Console.WriteLine(await new Handler().HandleAsync(job!));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 { "count" => new CountJob(id, parts[2]), _ => null, };}abstract record Job(int Id);sealed record CountJob(int Id, string Text) : Job(Id);class Handler{ public ValueTask<string> HandleAsync(Job job) => job switch { CountJob count => ValueTask.FromResult(count.Text.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length.ToString()), _ => throw new UnreachableException($"unknown job {job.GetType().Name}"), };}
Text
CountJob { Id = 3, Text = two words }2
More ideas, in rising order of difficulty:
Add jitter to the backoff, by passing a random source in through a constructor so that checks stay exact.
Report each job's elapsed time, using a TimeProvider.
Stop feeding new jobs after cancellation, and report the unread ones. What does invariant 1 mean now?
Give jobs priorities, using a PriorityQueue behind a lock. How do you keep backpressure?
Optional local setup
To run this on real threads, download the C# job runner. It holds the same source as the tabs, along with a project file, sample input and a README. Install the .NET 10 SDK from dotnet.microsoft.com, open a terminal in the extracted folder, and run:
Shell
dotnet --versiondotnet run < sample-input.txtdotnet run --property:Checks=true
In Windows PowerShell, use Get-Content sample-input.txt | dotnet run in place of the second line.
What changes on your computer
The output is the same, but much else differs:
Workers really run at once on the thread pool, so a data race becomes possible. Runner shares only channels, and the counters in the checks use Interlocked and lock, so they stay correct. Try changing Interlocked.Increment(ref running) to running++ in CountingHandler, and run the checks a few times.
Thread, .Result and .Wait() all work, and Parallel.For really does run on several cores. Blocking is still a poor choice in code like this: a blocked pool thread can't run other work.
A CPU-heavy handler no longer holds up everything else. Try one, with Task.Run and without.
Environment.Exit works after an await, although returning an exit code remains the cleaner style.
This is why the course kept repeating "safe in every runtime". Passing here shows that the logic is right. Safety across threads comes from the design: pass ownership through channels, and limit what's shared.
Completion is saved in this browser only. It does not measure mastery.