Chapter 2. Async Basics

This chapter introduces you to the basics of using async and await for asynchronous operations. Here, we’ll only deal with naturally asynchronous operations, which are operations such as HTTP requests, database commands, and web service calls.

If you have a CPU-intensive operation that you want to treat as though it were asynchronous (e.g., so that it doesn’t block the UI thread), then see Chapter 4 and Recipe 8.4. Also, this chapter only deals with operations that are started once and complete once; if you need to handle streams of events, then see Chapters 3 and 6.

2.1 Pausing for a Period of Time

Problem

You need to (asynchronously) wait for a period of time. This is a common scenario when unit testing or implementing retry delays. It also comes up when coding simple timeouts.

Solution

The Task type has a static method Delay that returns a task that completes after the specified time.

The following example code defines a task that completes asynchronously. When faking an asynchronous operation, it’s important to test synchronous success and asynchronous success, as well as asynchronous failure. The following example returns a task used for the asynchronous success case:

async Task<T> DelayResult<T>(T result, TimeSpan delay)
{
  await Task.Delay(delay);
  return result;
}

Exponential backoff is a strategy in which you increase the delays between retries. Use it when working with web services to ensure that the server doesn’t get flooded with retries. ...

Get Concurrency in C# Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.