liveBook · Manning

GetAsyncEnumerator

As explained in C# Concurrency: Asynchronous and multithreaded programming

GetAsyncEnumerator is a method that obtains an asynchronous enumerator for traversing an asynchronous sequence, optionally accepting a cancellation token.

GetAsyncEnumerator obtains an IAsyncEnumerator<T> for an IAsyncEnumerable<T>. It is not itself asynchronous and should return quickly; asynchronous initialization belongs in MoveNextAsync. section 14.1

The method parallels IEnumerable<T>.GetEnumerator, but supports await foreach and an optional CancellationToken. Because await foreach generates the call, pass cancellation through WithCancellation. section 14.3 section 14.1

Cancel an asynchronous iteration

await foreach (var item in collection.WithCancellation(token)) { Console.WriteLine(item); } section 14.3

How C# Concurrency: Asynchronous and multithreaded programming covers it

How deep it goes
Explains the interface contract and compiler-generated cancellation path, but defers detailed enumerator implementation.
Examples
Uses await foreach with WithCancellation and an async iterator whose delay observes an EnumeratorCancellation token.
What it assumes
Assumes familiarity with foreach and IEnumerable<T>, then extends that model through await foreach and asynchronous enumerator interfaces.
What you can do after
Apply it via IAsyncEnumerable<T> and WithCancellation to enumerate asynchronous data while forwarding cancellation.
How it connects
Connects IAsyncEnumerable<T>, IAsyncEnumerator<T>, await foreach, MoveNextAsync, CancellationToken, and WithCancellation.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of C# Concurrency: Asynchronous and multithreaded programming. The section links point to the parts of the book it draws on.