In C# library code, what does ConfigureAwait(false) on an await foreach loop configure, and why can the loop body still run on the captured context?
answer
- two sides, two sets of awaits
- the consumer's MoveNextAsync and DisposeAsync
- the iterator's own awaits capture separately
- inline continuation on the completing thread
basics
~20 ssource.ConfigureAwait(false) configures only the awaits that await foreach generates on MoveNextAsync and DisposeAsync. Awaits inside the async iterator are configured by the iterator's own code; if they capture the context, the loop body can still run there.
solid answer
~40 s`await foreach` by default resumes on the captured `SynchronizationContext`, like any await. `source.ConfigureAwait(false)` (an extension on `TaskAsyncEnumerableExtensions` returning `ConfiguredCancelableAsyncEnumerable<T>`) tells the loop not to capture the context when it awaits `MoveNextAsync()` and `DisposeAsync()`. It does not reach inside the producer: an async iterator's own `await`s capture whatever context is current where they run. If the iterator awaits without `ConfigureAwait(false)`, it resumes on the context, reaches `yield return` there and completes `MoveNextAsync()` on that thread; the loop's continuation, which no longer asks for the context, can then run inline on that same thread, so the loop body is still on the context. In a library, put `ConfigureAwait(false)` on the `await foreach` **and** on every `await` inside your async iterators.
code
csharp · 34 linesvar thread = new Thread(() =>
{
SynchronizationContext.SetSynchronizationContext(new PostingContext());
ConsumeAsync().GetAwaiter().GetResult();
});
thread.Start();
thread.Join();
static async Task ConsumeAsync()
{
await foreach (int page in PagesAsync().ConfigureAwait(false))
Console.WriteLine($"loop body, page {page}: on context = {SynchronizationContext.Current is not null}");
}
static async IAsyncEnumerable<int> PagesAsync()
{
for (int page = 1; page <= 2; page++)
{
await Task.Delay(20); // no ConfigureAwait(false): resumes on the context
yield return page;
}
}
// Stand-in for a UI context: runs every posted continuation with itself installed
sealed class PostingContext : SynchronizationContext
{
public override void Post(SendOrPostCallback d, object? state) =>
ThreadPool.QueueUserWorkItem(_ =>
{
SetSynchronizationContext(this);
d(state);
SetSynchronizationContext(null);
});
}go deeper
Recall that await foreach captures the context by default and that source.ConfigureAwait(false) is how a library loop opts out.
Explain which awaits the setting covers, MoveNextAsync and DisposeAsync in the consumer, and that the iterator's own awaits are configured separately.
Trace why a loop body can still land on a UI thread: the iterator resumes on the context, completes MoveNextAsync there, and the consumer continues inline.
Be ready to defend a library rule that configures both sides, and to explain why application code that touches UI keeps the default.
## The default: await foreach captures the context Every `await` in C#, unless told otherwise, captures the current **SynchronizationContext** (or, failing that, a non-default `TaskScheduler`) and resumes the rest of the method there. On a UI thread that means "back on the UI thread"; in a console app or an ASP.NET Core request there is usually no context to capture. Microsoft's documentation states the same rule for asynchronous sequences: by default, the `await foreach` statement processes stream elements in the captured context. Library code avoids that capture so its continuations do not queue behind a busy UI thread or deadlock a caller that blocks on it. The general rule and its deadlocks are covered with contexts and deadlocks; what is specific to asynchronous sequences is *where* the setting applies. ## What ConfigureAwait on the sequence configures ```csharp await foreach (var page in PagesAsync().ConfigureAwait(false)) { ... } ``` `TaskAsyncEnumerableExtensions.ConfigureAwait<T>(this IAsyncEnumerable<T>, bool continueOnCapturedContext)` wraps the sequence in a `ConfiguredCancelableAsyncEnumerable<T>`. When `await foreach` runs over it, the awaits **the loop itself generates** are configured: - the `await` on each `MoveNextAsync()`; - the `await` on `DisposeAsync()` when the loop ends. It chains with cancellation in either order, `source.WithCancellation(token).ConfigureAwait(false)`, because the wrapper type has both methods. ## What it does not configure The producer is a separate method. An async iterator, a method marked `async` returning `IAsyncEnumerable<T>` with `yield return`, contains its own `await` expressions, and each of those captures whatever context is current **on the thread where it runs**. The consumer's setting is not passed to them; it cannot be, because `GetAsyncEnumerator` only takes a `CancellationToken`. Here is what goes wrong when only the consumer is configured: 1. The consumer, running on a thread with a context, calls `MoveNextAsync()`. The iterator body runs synchronously on that same thread up to its first incomplete `await`. 2. That `await` captures the context, because the iterator did not say `ConfigureAwait(false)`. 3. When the awaited I/O finishes, the iterator's continuation is posted to the context and runs there, reaches `yield return`, and completes the `MoveNextAsync()` task on the context's thread. 4. The consumer's continuation does not need the context, so it is free to run inline on the thread that completed the task, which is the context's thread. 5. The loop body runs on the context, and the next `MoveNextAsync()` call starts the cycle again. The example below makes this visible with a small `SynchronizationContext` that stands in for a UI thread. With `ConfigureAwait(false)` only on the loop, both loop bodies report that they are on the context. Adding `.ConfigureAwait(false)` to the `Task.Delay` inside the iterator flips both to off the context. ## The full matrix, measured on .NET 10 | Consumer `ConfigureAwait` | Iterator's awaits | Iterator resumes on | Loop body ran on | |---|---|---|---| | default (`true`) | default | context | context | | default (`true`) | `false` | thread pool | context | | `false` | default | context | context | | `false` | `false` | thread pool | thread pool | Only the last row gets everything off the context. Note that `ConfigureAwait(false)` means "**need not** resume on the context", never "will move off it": when the awaited work completes on the context's thread, the continuation can run right there. ## The library rule For code shipped in a shared library: 1. write `ConfigureAwait(false)` on every `await` inside each async iterator you author, exactly as in ordinary async methods; 2. write `.ConfigureAwait(false)` on every `await foreach` the library performs, combined with `.WithCancellation(token)` when a token is passed; 3. for `await using` over an `IAsyncDisposable` enumerator, use its own `ConfigureAwait` overload, a detail covered with async disposal; 4. remember that the setting does not travel across method boundaries: each method configures only its own awaits. Application code that needs to touch UI controls inside the loop does the opposite and keeps the default, which is why a library must never make that choice for its callers by leaving its own awaits unconfigured. ## Checking a library for this The bug is invisible in a console app or a web host, because neither installs a context. To catch it: - run the library's async sequences under a test `SynchronizationContext`, like the one in the example, and assert that the producer's continuations never reach its `Post` method; - turn on the CA2007 analyzer rule ("Do not directly await a Task"), which is off by default, for library projects; the analyzers in the .NET 10 SDK report an unconfigured `await foreach` as well as each unconfigured `await` inside the iterator.
- Does ConfigureAwait(false) on the consumer change where the iterator's body first starts running?No. `MoveNextAsync()` runs the iterator body synchronously on the caller's thread until its first incomplete `await`, whatever the consumer configured. The consumer's setting only affects where the consumer resumes after that await completes, so the iterator's first await still sees the caller's context and captures it unless the iterator configures it.
- Is ConfigureAwait(false) on await foreach needed in an ASP.NET Core app?Not for correctness: ASP.NET Core installs no `SynchronizationContext`, so there is nothing to capture and the setting changes nothing there. Library code still writes it, because the same library may be called from a desktop app or a test runner that does install a context.
- ConfigureAwait(false) on await foreach also configures every await inside the iterator.
- An async iterator inherits the consumer's ConfigureAwait setting through GetAsyncEnumerator.
- ConfigureAwait(false) guarantees the loop body runs on a thread-pool thread.
- await foreach never captures a SynchronizationContext, so ConfigureAwait is pointless there.
- You cannot use WithCancellation and ConfigureAwait on the same await foreach.