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.