How would you combine yield return with async/await to build an IAsyncEnumerable<T>-producing async iterator method?
Short answer
Mark the method 'async' AND have it return IAsyncEnumerable , then you can use 'await' for asynchronous work AND 'yield return' to produce elements within the SAME method — the consumer then uses 'await foreach' to consume the resulting asynchronous stream, awaiting each element…
Advertisement
AModel answer
Mark the method 'async' AND have it return IAsyncEnumerable<T>, then you can use 'await' for asynchronous work AND 'yield return' to produce elements within the SAME method — the consumer then uses 'await foreach' to consume the resulting asynchronous stream, awaiting each element as it becomes available.
public async IAsyncEnumerable<string> FetchPagesAsync(string url) {
string? next = url;
while (next != null) {
var response = await httpClient.GetAsync(next); // async work
var page = await response.Content.ReadAsStringAsync();
yield return page; // yields a value
next = ExtractNextUrl(page);
}
}Real-world example
Streaming paginated API results one page at a time, combining asynchronous HTTP calls with lazy, incremental enumeration.
Likely follow-ups
- How would you add cancellation support to an async iterator method using the [EnumeratorCancellation] attribute?
Related topics