liveBook · Manning

CancellationToken

As explained in .NET in Action, Second Edition

A cancellation token is a .NET value that communicates a cooperative request for an operation to stop.

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

How .NET in Action, Second Edition covers it

How deep it goes
Shows an explicit parameter, a pre-request check, and token propagation into HTTP and JSON APIs.
Examples
Uses an asynchronous comic lookup and a search that shares a token across lookup tasks.
What it assumes
Assumes familiarity with C# methods while explaining the token-and-source relationship through a pager analogy.
What you can do after
Apply it by accepting a token, checking for cancellation, and passing it to asynchronous operations.
How it connects
Connects CancellationTokenSource with Task, async/await, HTTP requests, JSON deserialization, and ASP.NET Core requests.

Also explained in

Compare how 2 books explain CancellationToken →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of .NET in Action, Second Edition. The section links point to the parts of the book it draws on.