chapter fourteen

14 Generating collections asynchronously – await foreach and IAsyncEnumerable

 

This chapter covers:

  • How await foreach works.
  • Using yield return in async methods
  • Iterating over asynchronous data using IAsyncEnumerable<T> and await foreach.

Sometimes we want to use foreach to iterate over a sequence of items we generate on the fly or retrieve from an external source, without first adding the entire set of items to a collection. For example, we’ve seen in chapter 8 (and later in chapter 13) how BlockingCollection<T>’s support for foreach makes it easy to use it to build a work queue. C# makes this easy with the yield return keyword we’ve discussed in chapter 2.

However, both the version of yield return we covered in chapter 2 and BlockingCollection<T> don’t support asynchronous programming.

In this chapter, we’ll cover the asynchronous version of foreach (called await foreach) and the yield return enhancement from C# 8 that allows us to use it for asynchronous code. And finally, we’ll use all of those to write an asynchronous version of BlockingCollection<T> and a fully asynchronous work queue.

14.1 Iterating over an asynchronous collection

14.2 Generating an asynchronous collection

14.3 Canceling an asynchronous collection

14.4 Other Options

14.5 IAsyncEnumerable<T> and LINQ

14.6 Example: Iterating over asynchronously retrieved data

14.7 Example: BlockingCollection<T>-like asynchronous queue

14.8 Summary