A CancellationToken communicates a request for asynchronous work to stop. A CancellationTokenSource supplies the token and can signal cancellation; the operation must notice the signal and stop cooperatively. Cancellation is not added to an async API automatically, so accepting a token explicitly is a useful habit. section 4.4
Listing 4.34 Modifying GetComic to be asynchronous
public static async Task<Comic?> GetComicAsync( #1
int number, #2
CancellationToken cancellationToken) #3
{
if (cancellationToken.IsCancellationRequested) #4
{
return null;
}
try
{
var path = number == 0 ? "info.0.json"
: $"{number}/info.0.json";
var stream = await client.GetStreamAsync( #5
path, cancellationToken); #6
return await JsonSerializer.DeserializeAsync<Comic>( #7
stream, cancellationToken: cancellationToken); #6
}
catch (AggregateException e)
when (e.InnerException is HttpRequestException)
{
return null;
}
catch (HttpRequestException)
{
return null;
}
catch (TaskCanceledException) #8
{
return null;
}
}
GetComicAsync checks IsCancellationRequested before making an HTTP request, then passes the token to both the HTTP call and asynchronous JSON deserialization. Here, an early cancellation returns null; another API might instead throw. section 4.4
A title search can give multiple GetComicAsync calls the same source token. Once a match is found, further results are no longer needed. ASP.NET Core can also signal a request’s cancellation token when a client disconnects. section 4.4

