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:
asyncTask<T>DelayResult<T>(Tresult,TimeSpandelay){awaitTask.Delay(delay);returnresult;}
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. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access