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.

Time cooperativeSpace O(1)Code C#
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

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.