yield return gives one value at a time, and await waits without blocking. Put them together and you have IAsyncEnumerable<T>: values that arrive over time, such as pages of an API or lines from a slow source. The job runner returns its outcomes this way, as each finishes.
await foreach
An async method can yield return, as long as it returns IAsyncEnumerable<T>. Each step of an await foreach can pause while the next value is produced, and nothing is produced until someone asks. Predict the order.
IAsyncEnumerable<int> numbers = CountAsync(2);
Console.WriteLine("created");
await foreach (int number in numbers)
{
Console.WriteLine($"got {number}");
}
static async IAsyncEnumerable<int> CountAsync(int limit)
{
Console.WriteLine("started");
for (int i = 1; i <= limit; i++)
{
await Task.Delay(1);
yield return i;
}
Console.WriteLine("finished");
}Check your prediction
created
started
got 1
got 2
finishedCompare this with Task<List<int>>, which gives nothing until everything is ready, and which must hold it all in memory. A stream delivers the first result quickly, and it uses memory for only one value at a time.
Paging through an API
A real use: an API returns a page at a time. The stream hides the paging, so the caller just sees items. If the caller stops early, later pages are never requested. Count the fetches below.
int fetches = 0;
await foreach (int item in AllItemsAsync())
{
Console.WriteLine(item);
if (item == 3)
{
break;
}
}
Console.WriteLine($"fetches: {fetches}");
async IAsyncEnumerable<int> AllItemsAsync()
{
for (int page = 0; ; page++)
{
int[] items = await FetchPageAsync(page);
if (items.Length == 0)
{
yield break;
}
foreach (int item in items)
{
yield return item;
}
}
}
async Task<int[]> FetchPageAsync(int page)
{
fetches++;
await Task.Delay(1);
return page < 5 ? new[] { page * 2 + 1, page * 2 + 2 } : Array.Empty<int>();
}Check your prediction
1
2
3
fetches: 2Cancellation
An iterator can't take a token in the usual way if the caller gets the stream from elsewhere. So the attribute [EnumeratorCancellation] marks a parameter that receives the token from WithCancellation. Cancelling then throws at the current wait. Runner.RunAsync uses this attribute.
using System.Runtime.CompilerServices;
using var source = new CancellationTokenSource();
try
{
await foreach (int tick in TicksAsync().WithCancellation(source.Token))
{
Console.WriteLine(tick);
if (tick == 2)
{
source.Cancel();
}
}
}
catch (OperationCanceledException)
{
Console.WriteLine("stopped");
}
static async IAsyncEnumerable<int> TicksAsync([EnumeratorCancellation] CancellationToken token = default)
{
for (int i = 1; ; i++)
{
await Task.Delay(1, token);
yield return i;
}
}Check your prediction
1
2
stoppedEarly exit runs finally
When a caller breaks out, the iterator's finally blocks and using declarations run. That's how a stream over a file or connection releases it, no matter how the loop ends. A consumer that stops isn't a leak.
await foreach (int value in ResourceAsync())
{
Console.WriteLine(value);
break;
}
Console.WriteLine("after loop");
static async IAsyncEnumerable<int> ResourceAsync()
{
Console.WriteLine("open");
try
{
for (int i = 1; i <= 3; i++)
{
await Task.Yield();
yield return i;
}
}
finally
{
Console.WriteLine("close");
}
}Check your prediction
open
1
close
after loopThere's one restriction: yield return can't appear in a try that has a catch, though it can in a try with finally. So to handle errors for a producer, catch around each step instead, and yield outside.
Your turn
Stream operators
Write two generic extension methods on IAsyncEnumerable<T>:
WhereAsync(Func<T, bool> test)passes on matching items.BatchAsync(int size)yieldsList<T>batches, including a final partial batch.
The second must throw ArgumentOutOfRangeException for a size below 1 at the call, not when the loop starts. To do that, make the public method a normal method which checks and then calls a private async iterator.
Build a test source yielding 1 to 9, keep the odd numbers, and print batches of 2. Then show that BatchAsync(0) throws without any loop.
When it works, it prints:
1,3
5,7
9
refused at the callawait foreach (int number in SourceAsync())
{
Console.WriteLine(number);
}
static async IAsyncEnumerable<int> SourceAsync()
{
for (int i = 1; i <= 9; i++)
{
await Task.Yield();
yield return i;
}
}Hint 1: the idea
Both are iterators that loop over their source and yield. The eager check is the only new part: split one method into a public guard and a private iterator.
Hint 2: a first step
Write WhereAsync as a static async IAsyncEnumerable<T> extension in a static class, and check it before you start on batches.
Show one solution
await foreach (List<int> batch in SourceAsync().WhereAsync(n => n % 2 == 1).BatchAsync(2))
{
Console.WriteLine(string.Join(",", batch));
}
try
{
SourceAsync().BatchAsync(0);
}
catch (ArgumentOutOfRangeException)
{
Console.WriteLine("refused at the call");
}
static async IAsyncEnumerable<int> SourceAsync()
{
for (int i = 1; i <= 9; i++)
{
await Task.Yield();
yield return i;
}
}
static class StreamExtensions
{
public static async IAsyncEnumerable<T> WhereAsync<T>(this IAsyncEnumerable<T> items, Func<T, bool> test)
{
await foreach (T item in items)
{
if (test(item))
{
yield return item;
}
}
}
public static IAsyncEnumerable<List<T>> BatchAsync<T>(this IAsyncEnumerable<T> items, int size)
{
ArgumentOutOfRangeException.ThrowIfLessThan(size, 1);
return Batches(items, size);
}
private static async IAsyncEnumerable<List<T>> Batches<T>(IAsyncEnumerable<T> items, int size)
{
var batch = new List<T>();
await foreach (T item in items)
{
batch.Add(item);
if (batch.Count == size)
{
yield return batch;
batch = new List<T>();
}
}
if (batch.Count > 0)
{
yield return batch;
}
}
}1,3
5,7
9
refused at the callCompletion is saved in this browser only. It does not measure mastery.