Async patterns: cancellation, timeouts and async streams
Course contents (16 lessons)
- The type system
- Records, structs and value equality
- Interfaces and abstract classes
- Generics and constraints
- Delegates, events and lambdas
- Querying and matching data
- LINQ in depth: deferred execution, grouping and joins
- IEnumerable versus IQueryable
- Pattern matching in modern C#
- Async and await: how Task really works
- Async patterns: cancellation, timeouts and async streams
- Application structure
- Dependency injection and service lifetimes
- Configuration, options and logging
- Data and web
- Entity Framework Core basics: DbContext, migrations and queries
- Building a minimal API with ASP.NET Core
- Unit testing with xunit
- Performance and the final project
- Performance basics: Span of T and fewer allocations
- Final project: a notes API with EF Core, DI and logging
Beyond the basics
In real applications, async code needs more than await. Users close the page and the request should stop. A downstream service hangs and you want to give up after five seconds. A thousand items need processing, but the other server allows only ten connections. This lesson covers the tools for those situations.
Cancellation
Cancellation in .NET is cooperative. A CancellationTokenSource creates a token. You pass the token to methods that support it. When someone calls Cancel(), the token changes state, and the methods that watch it throw an OperationCanceledException. Nothing is killed by force. The code has to check, and it usually does so for you if you pass the token down.
// 1. Cancel after a timeout
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(700));
try
{
await LongJobAsync("export", cts.Token);
}
catch (OperationCanceledException)
{
Console.WriteLine("Export was cancelled.");
}
// 2. Limit concurrency
var gate = new SemaphoreSlim(3);
var tasks = Enumerable.Range(1, 8).Select(async i =>
{
await gate.WaitAsync();
try
{
Console.WriteLine($"Start {i} (running now: {3 - gate.CurrentCount})");
await Task.Delay(200);
}
finally
{
gate.Release();
}
});
await Task.WhenAll(tasks);
// 3. Async streams
await foreach (int n in CountDownAsync(3))
{
Console.WriteLine($"T-minus {n}");
}
// 4. Several failures from WhenAll
var failing = new[] { Fail("A"), Fail("B") };
var all = Task.WhenAll(failing);
try
{
await all;
}
catch
{
foreach (Exception e in all.Exception!.InnerExceptions)
{
Console.WriteLine($"Failure: {e.Message}");
}
}
static async Task LongJobAsync(string name, CancellationToken token)
{
for (int step = 1; step <= 10; step++)
{
token.ThrowIfCancellationRequested();
Console.WriteLine($"{name}: step {step}");
await Task.Delay(200, token);
}
}
static async IAsyncEnumerable<int> CountDownAsync(int from)
{
for (int i = from; i >= 1; i--)
{
await Task.Delay(100);
yield return i;
}
}
static async Task Fail(string name)
{
await Task.Delay(10);
throw new InvalidOperationException($"{name} failed");
}
Walking through it
The first block creates a source that cancels itself after 700 milliseconds. The long job loops through ten steps. At each step it calls ThrowIfCancellationRequested, and Task.Delay(200, token) also watches the token. After about three steps the token fires, an OperationCanceledException is thrown, and we catch it. A cancelled operation is not an error. It is an expected outcome, so catch it separately from real failures.
The guidance I give teams is simple. Every async method that does I/O should accept a CancellationToken as its last parameter and pass it down. In ASP.NET Core, a token for the request is available to endpoints. Passing it down means that when the client disconnects, your database query can stop.
The second block limits concurrency. A SemaphoreSlim(3) allows three holders at once. WaitAsync waits asynchronously when all slots are taken, and Release in the finally block always frees a slot. The output shows never more than three running. This pattern is how you call an API that has a rate limit without flooding it. Parallel.ForEachAsync is another option when you have a collection and want a built-in way to cap parallelism.
The third block uses IAsyncEnumerable<T>. A method with async and yield return produces items over time, and the caller reads them with await foreach. This suits data that arrives in pieces: rows streamed from a database, lines from a large file, messages from a queue. The caller can start work on the first item before the last one exists.
The last block shows a subtle point. When you await a WhenAll and several tasks fail, the await rethrows only the first exception. To see all of them, keep the task and read its Exception.InnerExceptions. In production code, this is how you avoid losing information.
Common mistakes
- Accepting a token and never using it. It must be passed to every call that supports it.
- Treating cancellation as a failure and logging it as an error.
- Forgetting to dispose a
CancellationTokenSource. Useusing. - Starting unlimited tasks for a huge list. Ten thousand simultaneous web requests will be refused or slow everything down.
- Releasing a semaphore outside
finally. One exception and the slot is lost for good.
Try it yourself
- Add a "press Enter to cancel" feature to
LongJobAsyncby callingcts.Cancel()when the user presses a key. - Write
WithTimeout<T>(Task<T> task, TimeSpan timeout)that throwsTimeoutExceptionif the task takes too long. Hint:task.WaitAsync(timeout)exists in modern .NET. - Change the concurrency limit to 2 and watch the output.
// 1. Cancel after a timeout
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(700));
try
{
await LongJobAsync("export", cts.Token);
}
catch (OperationCanceledException)
{
Console.WriteLine("Export was cancelled.");
}
// 2. Limit concurrency
var gate = new SemaphoreSlim(3);
var tasks = Enumerable.Range(1, 8).Select(async i =>
{
await gate.WaitAsync();
try
{
Console.WriteLine($"Start {i} (running now: {3 - gate.CurrentCount})");
await Task.Delay(200);
}
finally
{
gate.Release();
}
});
await Task.WhenAll(tasks);
// 3. Async streams
await foreach (int n in CountDownAsync(3))
{
Console.WriteLine($"T-minus {n}");
}
// 4. Several failures from WhenAll
var failing = new[] { Fail("A"), Fail("B") };
var all = Task.WhenAll(failing);
try
{
await all;
}
catch
{
foreach (Exception e in all.Exception!.InnerExceptions)
{
Console.WriteLine($"Failure: {e.Message}");
}
}
static async Task LongJobAsync(string name, CancellationToken token)
{
for (int step = 1; step <= 10; step++)
{
token.ThrowIfCancellationRequested();
Console.WriteLine($"{name}: step {step}");
await Task.Delay(200, token);
}
}
static async IAsyncEnumerable<int> CountDownAsync(int from)
{
for (int i = from; i >= 1; i--)
{
await Task.Delay(100);
yield return i;
}
}
static async Task Fail(string name)
{
await Task.Delay(10);
throw new InvalidOperationException($"{name} failed");
}
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account