Cancellation and timeouts
suggest changeIn C# and .NET, asynchronous task cancellation is cooperative: a caller signals that work should stop, and the executing method observes this signal and terminates cleanly without leaving state corrupted. This pattern is implemented using CancellationTokenSource (CTS) and CancellationToken (CT).
How Cooperative Cancellation Works
The caller instantiates a CancellationTokenSource and passes its Token to asynchronous methods:
using System;
using System.Threading;
using System.Threading.Tasks;
public class Worker
{
public static async Task DoWorkAsync(CancellationToken cancellationToken)
{
for (int i = 0; i < 100; i++)
{
// Throws OperationCanceledException if cancellation was requested
cancellationToken.ThrowIfCancellationRequested();
Console.WriteLine($"Working step {i}...");
// Pass token into built-in async methods so delay aborts immediately
await Task.Delay(500, cancellationToken);
}
}
}
Caller triggering manual cancellation:
using var cts = new CancellationTokenSource();
// Cancel after 1.5 seconds from another thread or task
_ = Task.Run(async () =>
{
await Task.Delay(1500);
cts.Cancel();
});
try
{
await Worker.DoWorkAsync(cts.Token);
}
catch (OperationCanceledException)
{
Console.WriteLine("Operation was cleanly canceled.");
}
Enforcing Timeouts with CancelAfter
To enforce a strict execution timeout, configure CancellationTokenSource with a duration:
// Automatically requests cancellation after 3 seconds:
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(3));
try
{
using var client = new HttpClient();
// Inflight HTTP request terminates if timeout expires
var response = await client.GetAsync("https://httpbin.org/delay/5", cts.Token);
}
catch (OperationCanceledException) when (cts.IsCancellationRequested)
{
Console.WriteLine("Request timed out after 3 seconds.");
}
Alternatively, call cts.CancelAfter(TimeSpan) dynamically on an existing source.
Modern Task Timeouts with Task.WaitAsync (.NET 6+)
Starting with .NET 6, any Task or Task<T> can be awaited with a timeout using WaitAsync(), without needing to construct a separate CTS:
Task<string> slowTask = FetchRemoteReportAsync();
try
{
// Awaits the task, but throws TimeoutException if not completed within 2 seconds
string report = await slowTask.WaitAsync(TimeSpan.FromSeconds(2));
Console.WriteLine(report);
}
catch (TimeoutException)
{
Console.WriteLine("Report retrieval timed out.");
}
WaitAsync() also accepts a CancellationToken alongside the timeout duration.
Combining Multiple Tokens (Linked Cancellation)
When a method needs to cancel if either a local timeout expires OR a global application shutdown signal is triggered, link them using CreateLinkedTokenSource:
public async Task ProcessJobAsync(CancellationToken appShutdownToken)
{
// Creates a local 5-second timeout
using var timeoutCts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
// Combines the shutdown token and the timeout token
using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(
appShutdownToken,
timeoutCts.Token
);
try
{
await ExecuteStepAsync(linkedCts.Token);
}
catch (OperationCanceledException)
{
if (appShutdownToken.IsCancellationRequested)
Console.WriteLine("Stopped due to application shutdown.");
else if (timeoutCts.IsCancellationRequested)
Console.WriteLine("Stopped due to job timeout.");
}
}
Best Practices
- Always forward
CancellationToken: In any async method that accepts aCancellationToken, pass it to every child asynchronous call (HttpClient,DbCommand,Stream.ReadAsync,Task.Delay). - Dispose
CancellationTokenSource: BecauseCancelAfterand timeout constructors initialize underlying system timers, always dispose theCancellationTokenSource(e.g., usingusing var cts = ...). - Catch
OperationCanceledException:TaskCanceledExceptionderives fromOperationCanceledException. CatchingOperationCanceledExceptionsafely handles both manual aborts and timeout cancellations.