liveBook · Manning

Task Parallel Library

As explained in .NET in Action, Second Edition

The Task Parallel Library is the .NET library for expressing task-based asynchronous and parallel operations.

The Task Parallel Library (TPL), used with C#’s async and await keywords, supports asynchronous work. A Task represents a unit of work that may run on the same thread or a separate thread. Tasks are useful for slow network and disk operations, when the CPU would otherwise spend time waiting. section 4.4

An asynchronous HTTP method can return Task<Comic?>, await a response stream, and await JSON deserialization. Pass a CancellationToken explicitly to APIs that accept one; cancellation is not added automatically. 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;
  }
}

The listing shows an async method that checks for cancellation before requesting a comic and passes the token into both I/O calls. section 4.4

Search for a comic by title

A synchronous search makes HTTP requests one at a time. Its asynchronous counterpart starts comic-fetching tasks and uses continuations to inspect results; a Stopwatch measures the search time. section 4.4

How .NET in Action, Second Edition covers it

How deep it goes
Defines Task and works through asynchronous HTTP fetching, cancellation-token passing, continuations, and an asynchronous caller.
Examples
Shows a timed comic-title search and code for fetching and deserializing comics asynchronously.
What it assumes
Builds on C# methods and HTTP-fetching code while defining Task before using it.
What you can do after
Apply it via the Task Parallel Library to write an asynchronous HTTP lookup that accepts cancellation.
How it connects
Connects Tasks with async/await, HTTP requests, JSON deserialization, cancellation tokens, and continuations.

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.