liveBook · Manning

WithCancellation

As explained in C# Concurrency: Asynchronous and multithreaded programming

WithCancellation is a .NET extension method that associates a cancellation token with an IAsyncEnumerable<T> for asynchronous iteration.

WithCancellation associates a CancellationToken with an IAsyncEnumerable<T> during await foreach. It returns a wrapper whose GetAsyncEnumerator passes the supplied token to the original sequence. section 14.3

Cancel an async iterator

Define the iterator parameter with [EnumeratorCancellation], then apply collection.WithCancellation(cancel.Token). The iterator must observe the token—for example, Task.Delay(1000, cancellationToken)—because the token is only a flag. Canceling before the loop starts can prevent subsequent values. section 14.3 section 14.8

await foreach(var item in collection.WithCancellation(token))

Use the extension directly in the await foreach clause to pass cancellation into asynchronous iteration. section 14.3

How C# Concurrency: Asynchronous and multithreaded programming covers it

How deep it goes
Explains the wrapper implementation and EnumeratorCancellation handoff, but defers stopping behavior to token-observing iterator code.
Examples
Uses an async iterator yielding two integers, a delayed second value, and cancellation before or during iteration.
What it assumes
Assumes familiarity with async/await, IAsyncEnumerable<T>, await foreach, and cancellation tokens.
What you can do after
Apply it via the WithCancellation extension method and implement token-aware async iterators.
How it connects
Connects IAsyncEnumerable<T>, await foreach, CancellationToken, and EnumeratorCancellation with asynchronous iterators.

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.