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
