Skip to content

Come Back Later

The Course
•
30 min study

Return to this page after two or three days, and again after about a week. Start each time with a blank editor. These challenges are extra review, outside Day 7's time estimate.

Retrieve: without looking, write a worker pool with a bounded channel, an outcome per job, and cancellation. Explain why Task.WhenAll over a thousand calls isn't a concurrency limit. State the rule that links Equals and GetHashCode.

Debug: predict the output of each program before you run it. Each one contains a classic mistake from this course. Explain the cause, then fix it.

Debug 1: the increment that vanished C#
var items = new List<Counter> { new Counter() };
items[0].Add();
Console.WriteLine(items[0].Value);

struct Counter
{
    public int Value { get; private set; }

    public void Add()
    {
        Value++;
    }
}
Check your prediction
Text
0
Debug 2: the error nobody saw C#
_ = FailAsync();
await Task.Delay(10);
Console.WriteLine("All good?");

static async Task FailAsync()
{
    await Task.Yield();
    throw new InvalidOperationException("lost");
}
Check your prediction
Text
All good?
Debug 3: the reader that would wait forever C#
using System.Threading.Channels;

Channel<int> channel = Channel.CreateUnbounded<int>();
channel.Writer.TryWrite(1);

using var safety = new CancellationTokenSource(20);
try
{
    await foreach (int value in channel.Reader.ReadAllAsync(safety.Token))
    {
        Console.WriteLine(value);
    }
    Console.WriteLine("finished");
}
catch (OperationCanceledException)
{
    Console.WriteLine("nobody called Complete");
}
Check your prediction
Text
1
nobody called Complete
Debug 4: a timeout or a cancel? C#
using var caller = new CancellationTokenSource();
caller.Cancel();

using var attempt = CancellationTokenSource.CreateLinkedTokenSource(caller.Token);

try
{
    await Task.Delay(1000, attempt.Token);
}
catch (OperationCanceledException) when (attempt.IsCancellationRequested)
{
    Console.WriteLine("reported as a timeout");
}
Check your prediction
Text
reported as a timeout

Transfer: build the method below from its description alone. Choose test cases that would catch a window off by one, and a lost item on failure.

Your turn

Exercise

Ordered results from unordered work

Write MapOrderedAsync<TIn, TOut>(IEnumerable<TIn> items, int workers, Func<TIn, Task<TOut>> work), an IAsyncEnumerable<TOut> that runs up to workers calls at once, and that yields results in the input order, as soon as each next result is ready. It reads the input lazily, starting at most workers calls ahead of what's been yielded. A failure in work reaches the caller when that item's turn comes.

Check the order with delays that finish in reverse, the peak concurrency, and a failure. Print Review checks passed if everything passes.

When every check passes, it prints:

Text
Review checks passed
Your workspace C#
await Task.Yield();
Console.WriteLine("Review checks passed");
Hint 1: the idea

A Queue<Task<TOut>> holds the running work in order. Before you yield the front, top the queue up to workers.

Hint 2: a first step

Write the iterator with workers of 1, which amounts to a plain loop. Then add the queue and the top-up. Awaiting the front task naturally rethrows its failure at the right moment.

Show one solution
C#
int failures = 0;

void Check(bool passed, string name)
{
    if (!passed)
    {
        Console.WriteLine($"FAILED: {name}");
        failures++;
    }
}

var seen = new List<int>();
await foreach (int value in MapOrderedAsync(new[] { 30, 20, 1 }, 3, async ms =>
{
    await Task.Delay(ms);
    return ms;
}))
{
    seen.Add(value);
}
Check(seen.SequenceEqual(new[] { 30, 20, 1 }), "keeps the input order");

var peakGate = new object();
int running = 0;
int peak = 0;
await foreach (int value in MapOrderedAsync(Enumerable.Range(1, 10), 2, async item =>
{
    int now = Interlocked.Increment(ref running);
    lock (peakGate)
    {
        peak = Math.Max(peak, now);
    }
    await Task.Delay(1);
    Interlocked.Decrement(ref running);
    return item;
}))
{
}
Check(peak == 2, "the peak equals the limit");

var before = new List<int>();
try
{
    await foreach (int value in MapOrderedAsync(new[] { 1, 2, 3 }, 2, async item =>
    {
        await Task.Yield();
        return item == 2 ? throw new InvalidOperationException("boom") : item;
    }))
    {
        before.Add(value);
    }
    Check(false, "a failure reaches the caller");
}
catch (InvalidOperationException)
{
    Check(before.SequenceEqual(new[] { 1 }), "earlier results still arrive");
}

if (failures == 0)
{
    Console.WriteLine("Review checks passed");
}

static async IAsyncEnumerable<TOut> MapOrderedAsync<TIn, TOut>(IEnumerable<TIn> items, int workers, Func<TIn, Task<TOut>> work)
{
    var running = new Queue<Task<TOut>>();
    using IEnumerator<TIn> source = items.GetEnumerator();
    while (true)
    {
        while (running.Count < workers && source.MoveNext())
        {
            running.Enqueue(work(source.Current));
        }
        if (running.Count == 0)
        {
            yield break;
        }
        yield return await running.Dequeue();
    }
}
Text
Review checks passed

Decide what to revisit

If Debug 3 or Debug 4 surprised you, rework the Day 3 and Day 4 checkpoints from a blank editor, since those mistakes cause real outages. If spans and pooling felt shaky, remember that you can write very good C# without them until a measurement says otherwise. If the link checker was out of reach, draw its flow on paper first: who writes, who completes, and who owns each piece of state?

From here, try the job runner on your own computer, and then build something real with these patterns. ASP.NET Core for web services, and System.Threading.RateLimiting and Polly for resilience, all build on what you've learned this week.

Was this article helpful?

Your response is saved on this device.