yield return async
Learn to write async iterator methods and yield return await.
yield return async
yield return produces an element into the stream and pauses. In an async IAsyncEnumerable<T> method each yield return sends the element to the consumer; the consumer waits until it asks for the next element with await foreach.
You can put await between two yield return statements to wait for input/output. Example: await Task.CompletedTask; yield return 1; await Task.CompletedTask; yield return 2;. This is used in scenarios like waiting for each row in a real database stream.
Stream production
An async stream can have multiple yield return in a row. Each one is produced as a separate element. Example: yield return 1; yield return 2; yield return 3; gives a stream of three elements.
You can also produce conditionally: if (n > 0) yield return n;. Use yield break to end the stream early. This is exactly like yield in synchronous iterators (IEnumerable); it just runs async.
Exercise Stream with yield return
Define static async IAsyncEnumerable<int> Evens(). In its body write await Task.CompletedTask;, yield return 2;, yield return 4;, yield return 6;. Make Main a static async Task Main. Sum with int sum = 0; await foreach (int n in Evens()) { sum += n; } and print with Console.WriteLine(sum);.
Show example solution
In Evens body write await Task.CompletedTask; yield return 2; yield return 4; yield return 6;. Make Main static async Task Main() and write int sum = 0; await foreach (int n in Evens()) { sum += n; } Console.WriteLine(sum);
Example solution:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
class Program
{
static async IAsyncEnumerable<int> Evens()
{
await Task.CompletedTask;
yield return 2;
yield return 4;
yield return 6;
}
static async Task Main()
{
int sum = 0;
await foreach (int n in Evens())
{
sum += n;
}
Console.WriteLine(sum);
}
}
Test yourself
-
What does yield return do?
- It produces an element into the stream and pauses
- It exits the method
- It awaits a Task
- It throws an error
Show answer
It produces an element into the stream and pauses — Correct. yield return produces an element into the stream and pauses.
-
Complete yield return
yield ____ 42;Show answer
yield return 42; -
What can be placed between yield returns?
- Only return
- await for waiting
- Thread.Sleep
- lock statement
Show answer
await for waiting — Correct. await for waiting can be placed between yield returns.