Asynchronous tests have a bad reputation, because the obvious way to write one is to wait "long enough" and hope. That produces tests that are slow, and that fail randomly on a busy machine. The fix is to control timing instead of guessing, and this checkpoint collects the techniques used by the job runner's checks.
Exiting with failure
There's a detail to get right first. Environment.Exit(1) works in the synchronous checks from the earlier courses, but in this browser runtime, calling it after an await hangs the run. Use return 1; from your top-level statements instead. That works everywhere, and it sets the exit code just the same.
await Task.Delay(1);
int failures = 1;
if (failures > 0)
{
Console.WriteLine("1 check failed");
return 1;
}
Console.WriteLine("All passed");
return 0;Check your prediction
1 check failed
Program exited with status 1.A gate replaces a sleep
TaskCompletionSource creates a task that you finish by hand. A fake handler that awaits it stays "in progress" for exactly as long as the test wants, so the test can inspect the state in the middle. RunContinuationsAsynchronously stops the continuation from running inside SetResult, which prevents surprises. It's a good habit to pass it.
var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
int started = 0;
int finished = 0;
Task work = WorkAsync();
await Task.Yield();
Console.WriteLine($"{started} started, {finished} finished");
gate.SetResult();
await work;
Console.WriteLine($"{started} started, {finished} finished");
async Task WorkAsync()
{
started++;
await gate.Task;
finished++;
}Check your prediction
1 started, 0 finished
1 started, 1 finishedA hang must fail, not freeze
If the code under test deadlocks, the test shouldn't wait forever. WaitAsync adds a limit to any task, and it fails with a clear error. Use a generous limit, because it's a safety net rather than a timing assumption. It only costs time when something is already broken.
var never = new TaskCompletionSource();
try
{
await never.Task.WaitAsync(TimeSpan.FromMilliseconds(20));
Console.WriteLine("finished");
}
catch (TimeoutException)
{
Console.WriteLine("FAILED: it hung");
}Check your prediction
FAILED: it hungCheck properties, not schedules
Don't assert the exact order of concurrent work, since a different machine may produce another valid order. Assert what must be true: every job produced one outcome, the number running at once never exceeded the limit, no work started after a cancellation. Then the test passes on any correct schedule, including the single thread here and the thread pool on your computer. The job runner's checks have passed in both.
Build it yourself
Test a concurrency limiter
The workspace has RunLimitedAsync, which runs an action for each item, with at most limit at once. Write checks for it, without any delays or sleeps of your own, for these properties:
- Every item is processed exactly once.
- The peak number running equals the limit: not above, and for enough items, not below.
- While the first batch is held at a gate, no more start.
- If an action throws, the exception reaches the caller, and every started action has finished by then.
- A failed action gives its slot back: with a limit of 2, after the first two items throw, the other items still run.
Exit with return 1 if anything fails, and print Limiter checks passed otherwise. Protect the awaits with WaitAsync. Then test your tests: remove the try and finally around the release in RunLimitedAsync (keep the Release call after the await), and run the checks again. Only check 5 should fail. Ask yourself why check 4 doesn't notice.
When every check passes, it prints:
Limiter checks passedawait RunLimitedAsync(new[] { 1, 2 }, 1, async item =>
{
await Task.Yield();
Console.WriteLine(item);
});
static async Task RunLimitedAsync<T>(IEnumerable<T> items, int limit, Func<T, Task> action)
{
var slots = new SemaphoreSlim(limit);
async Task RunOneAsync(T item)
{
await slots.WaitAsync();
try
{
await action(item);
}
finally
{
slots.Release();
}
}
await Task.WhenAll(items.Select(RunOneAsync));
}Hint 1: the idea
The peak is measured by a fake action: increment a counter on entry, record the maximum, await, and decrement on exit. A gate holds the first actions in progress for property 3.
Hint 2: a first step
Write a Check local function and property 1, using a ConcurrentDictionary or a counted list. Use await Task.Yield() a few times to let queued work start before you read the counters.
Show one solution
int failures = 0;
TimeSpan limit = TimeSpan.FromSeconds(5);
void Check(bool passed, string name)
{
if (!passed)
{
Console.WriteLine($"FAILED: {name}");
failures++;
}
}
int[] items = Enumerable.Range(1, 12).ToArray();
var seen = new List<int>();
int running = 0;
int peak = 0;
await RunLimitedAsync(items, 3, async item =>
{
int now = Interlocked.Increment(ref running);
lock (seen)
{
seen.Add(item);
peak = Math.Max(peak, now);
}
await Task.Yield();
Interlocked.Decrement(ref running);
}).WaitAsync(limit);
Check(seen.Order().SequenceEqual(items), "each item is processed once");
Check(peak == 3, "the peak equals the limit");
var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
int started = 0;
Task held = RunLimitedAsync(items, 2, async item =>
{
Interlocked.Increment(ref started);
await gate.Task;
});
for (int i = 0; i < 10; i++)
{
await Task.Yield();
}
Check(started == 2, "no more start while a batch is held");
gate.SetResult();
await held.WaitAsync(limit);
Check(started == items.Length, "the rest start after the gate opens");
int finished = 0;
int begun = 0;
try
{
await RunLimitedAsync(items, 2, async item =>
{
Interlocked.Increment(ref begun);
try
{
await Task.Yield();
if (item == 3)
{
throw new InvalidOperationException("boom");
}
}
finally
{
Interlocked.Increment(ref finished);
}
}).WaitAsync(limit);
Check(false, "a failure reaches the caller");
}
catch (InvalidOperationException)
{
}
Check(begun == finished, "all started work has finished");
int ranAfterFailures = 0;
try
{
await RunLimitedAsync(new[] { 1, 2, 3, 4 }, 2, async item =>
{
await Task.Yield();
if (item <= 2)
{
throw new InvalidOperationException("boom");
}
Interlocked.Increment(ref ranAfterFailures);
}).WaitAsync(TimeSpan.FromSeconds(1));
}
catch (InvalidOperationException)
{
}
catch (TimeoutException)
{
}
Check(ranAfterFailures == 2, "a failed action gives its slot back");
if (failures > 0)
{
return 1;
}
Console.WriteLine("Limiter checks passed");
return 0;
static async Task RunLimitedAsync<T>(IEnumerable<T> items, int limit, Func<T, Task> action)
{
var slots = new SemaphoreSlim(limit);
async Task RunOneAsync(T item)
{
await slots.WaitAsync();
try
{
await action(item);
}
finally
{
slots.Release();
}
}
await Task.WhenAll(items.Select(RunOneAsync));
}Limiter checks passedWithout the finally, a throwing action never returns its slot. Check 4 can't see that: one item fails, so one of the two slots is lost, but the other slot carries on through the remaining items and the run finishes. A leak that only shrinks capacity looks like success. Check 5 makes the leak total. Items 1 and 2 take both slots and fail, so with the bug items 3 and 4 wait forever, the one-second WaitAsync turns the hang into a TimeoutException, and ranAfterFailures stays at 0. That's the general lesson of mutating your own code: when a deliberate bug passes every check, the checks have a gap, and the bug tells you what the missing check must provoke.
Completion is saved in this browser only. It does not measure mastery.