CancellationToken and async requests
Cancellation is a signal the operation must observe. Passing a token to async I/O lets the caller request that work stop.
Watch it animatedStep through it, with the running line highlighted. Free with an account.The idea
The caller owns the CancellationTokenSource and passes its token to the operation. Calling Cancel sends a cooperative signal. HttpClient observes the token and ends the request by throwing OperationCanceledException; the task then completes as cancelled.
Code
using var cts = new CancellationTokenSource();
Task<string> task = GetDataAsync(cts.Token);
cts.Cancel(); // signal cancellation while the request is running
try { await task; } catch (OperationCanceledException) { /* expected here */ }
static async Task<string> GetDataAsync(CancellationToken token) {
try {
return await httpClient.GetStringAsync(url, token);
}
catch (OperationCanceledException) {
Console.WriteLine("Request cancelled");
throw;
}
}Tips
- Cancellation does not forcibly stop a thread. The operation must accept and observe the token.
- Pass the same token through each layer of async work, and avoid catching OperationCanceledException as though it were an ordinary success.
In the .NET library
ASP.NET Core supplies a request-aborted token for incoming requests. Passing it to database and HTTP calls can stop unnecessary work when the client disconnects.