Chapter 7. Utilities for Async Code

The Task-based Asynchronous Pattern is designed to make it easy to create utilities for working with Tasks. Because all TAP methods give you a Task, any special behavior we write for one TAP method, we can reuse against others. In this chapter, we’ll look at some utilities for working with Task, including:

  • Methods that look like TAP methods, but have useful special behavior rather than being asynchronous calls themselves

  • Combinators, which are methods which process Tasks, generating useful new Tasks based on them

  • Tools for canceling and showing progress during asynchronous operations

While a lot of these utilities already exist, it’s useful to see how easy it is to implement them yourself, in case you need similar tools in the future that aren’t provided by the .NET Framework.

Delaying for a Period of Time

The most simple long-running operation that you might want to perform is possibly to do absolutely nothing for a length of time. This is the equivalent of Thread.Sleep in the synchronous world. In fact, you could implement it using Thread.Sleep in conjunction with Task.Run:

await Task.Run(() => Thread.Sleep(100));

But this simple approach is wasteful. A thread is being used solely to block for the time period, which is a waste. There is already a way to have .NET call your code back after a period of time without using any threads, the System.Threading.Timer class. A more efficient approach would be to set up a Timer, then use a TaskCompletionSource ...

Get Async in C# 5.0 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.