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 may 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 chapters 8 and 13 how BlockingCollection<T>’s support for foreach makes it easy to use for building a work queue. C# makes this easy with the yield return keyword, as discussed in chapter 2. However, both the versions 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, which allows us to use it for asynchronous code. And finally, we’ll employ 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

Summary