In C#, does a value in an AsyncLocal<T> survive an await with ConfigureAwait(false), and why does SynchronizationContext.Current behave differently?
answer
- two contexts, two jobs
- what is visible vs where it runs
- flows unless suppressed
- captured and posted, not flowed
- the callee's changes stay inside
basics
~10 sYes. AsyncLocal<T> lives in the ExecutionContext, which every await carries to its continuation regardless of ConfigureAwait. SynchronizationContext.Current is captured and posted to, not flowed, so a thread-pool continuation or a Task.Run delegate sees null.
solid answer
~40 sThere are two contexts with different jobs. `ExecutionContext` answers "what ambient state is visible": it holds `AsyncLocal<T>` values, and the async method builders capture it at every suspending await and restore it in the continuation, whatever thread that is. `ConfigureAwait(false)` does not touch it. `SynchronizationContext` answers "where should code run": the task awaiter captures it and posts the continuation to it, but the runtime deliberately suppresses it from flowing inside the `ExecutionContext`, so code that runs on a pool thread, including a `Task.Run` delegate started from the UI thread, sees `SynchronizationContext.Current` as `null`. One more rule: an async method's changes to an `AsyncLocal<T>` do not flow back to its caller, because the builder restores the caller's context when the method returns its task.
code
csharp · 23 linesvar correlationId = new AsyncLocal<string?>();
correlationId.Value = "refresh-42";
await Task.Delay(50).ConfigureAwait(false);
Console.WriteLine($"after ConfigureAwait(false): {correlationId.Value}");
Console.WriteLine($"inside Task.Run: {await Task.Run(() => correlationId.Value)}");
await StampAsync(correlationId);
Console.WriteLine($"caller after StampAsync: {correlationId.Value}");
Task<string?> unflowed;
using (ExecutionContext.SuppressFlow())
{
unflowed = Task.Run<string?>(() => correlationId.Value);
}
Console.WriteLine($"Task.Run under SuppressFlow: {await unflowed ?? "null"}");
static async Task StampAsync(AsyncLocal<string?> local)
{
local.Value = "set-in-callee";
await Task.Yield();
Console.WriteLine($"callee after its own await: {local.Value}");
}go deeper
Recall that AsyncLocal<T> keeps a value with an async operation even when the thread changes.
Contrast the two contexts: ExecutionContext carries state and always flows, SynchronizationContext picks the thread and is only captured.
Explain why a callee's AsyncLocal<T> change is invisible to the caller, why Task.Run sees a null SynchronizationContext, and when SuppressFlow is the right tool.
Judge ambient state as a design choice: AsyncLocal<T> makes correlation easy but hides dependencies and leaks into background work unless flow is suppressed.
## Two contexts, two questions .NET async code carries two different kinds of context, and mixing them up produces confident wrong answers. | | `ExecutionContext` | `SynchronizationContext` | |---|---|---| | Question it answers | what ambient state is visible | where the code should run | | Who handles it at an await | the async method builders | the `Task` awaiter | | Flows across await | yes, for every awaitable | no; captured and posted to | | Turned off by | `ExecutionContext.SuppressFlow()` (for queued work) | `ConfigureAwait(false)` | `ExecutionContext` is the container for ambient data that should follow a logical operation from thread to thread. Its user-facing piece is `AsyncLocal<T>`: a value stored in it is visible to the code that set it and to everything that code starts or awaits later. Logging scopes, correlation IDs and culture-like settings are typical uses. ## ExecutionContext flows across every await When an `await` suspends, the async method builder captures the current `ExecutionContext`, and when the method resumes it runs the continuation inside that context. Microsoft's documentation states that this "applies regardless of what kind of awaitable you use". `ConfigureAwait(false)` only changes the **SynchronizationContext** decision, so: - after `await x.ConfigureAwait(false)`, the method may be on a different thread, and the `AsyncLocal<T>` value is still there; - a `Task.Run` delegate sees the values set before it was queued, because `Task.Run`, `ThreadPool.QueueUserWorkItem` and similar APIs capture the `ExecutionContext` too; - the value is captured **when the work is queued**: if the caller changes the `AsyncLocal<T>` after calling `Task.Run`, the delegate still sees the earlier value, because each assignment creates a new immutable context instead of editing the captured one; - inside `using (ExecutionContext.SuppressFlow())`, work queued with `Task.Run` starts **without** those values. `SuppressFlow` affects work queued while it is active; it is not a per-await switch. ## Changes do not flow back up `AsyncLocal<T>` values flow **down** into callees, not back up: 1. The caller sets `correlationId.Value = "refresh-42"` and calls `await StampAsync()`. 2. `StampAsync` sets the value to `"set-in-callee"`, awaits, and still sees its own value after the await. 3. When `StampAsync` returns its task, the builder's `Start` method restores the caller's `ExecutionContext`. Back in the caller, the value is `"refresh-42"` again. This holds even if the async method never awaits at all: the restore happens when `Start` returns. A plain synchronous method that sets the value has no builder around it, so its change **is** visible to the caller afterwards. Mutating an object stored in an `AsyncLocal<T>` is different again: the context holds a reference, so the change to the object is shared by everyone holding it. ## SynchronizationContext does not flow `SynchronizationContext` is technically one of the sub-contexts an `ExecutionContext` can carry, but the runtime's async plumbing uses internal overloads that explicitly **exclude** it from flowing. The reason is meaning. `SynchronizationContext.Current` is supposed to say "the environment I am running in now". If it flowed, a thread-pool thread running a `Task.Run` delegate started from a button handler would report the UI context as current; every bare `await` inside that delegate would then post its continuation back to the UI thread, and the CPU work that `Task.Run` was meant to move off the UI thread would come straight back to it. Because it does not flow: - inside `Task.Run(() => ...)` started from the UI thread, `SynchronizationContext.Current` is `null`; - after `await x.ConfigureAwait(false)` resumes on a pool thread, it is `null`; - the async method builder also restores the caller's `SynchronizationContext` when the method returns its task, so a method that installs its own context does not leak it to the caller. ## Why it matters in interviews and in code - Logging and tracing code that relies on `AsyncLocal<T>` keeps working in libraries that use `ConfigureAwait(false)` everywhere; there is no trade-off between the two. - "ConfigureAwait(false) loses my user or culture context" is usually a confusion between the two kinds: ambient data survives; only the thread, and therefore thread-affine objects such as UI controls, changes. - A fire-and-forget `Task.Run` inherits the request's ambient values. If that is undesirable, for example a background job should not carry a caller's correlation ID, start it under `ExecutionContext.SuppressFlow()`. The summary interviewers listen for: **ExecutionContext flows, SynchronizationContext is captured**. One decides what you can see, the other decides where you run.
- In C#, if a synchronous helper sets an AsyncLocal<T> value, does the caller see the new value afterwards?Yes. An async method restores the caller's `ExecutionContext` when it returns its task, because its builder's `Start` method does that. A plain synchronous method has no builder around it: its assignment replaces the thread's current context and nothing restores the old one, so the caller sees the new value when the helper returns.
- Why does the C# runtime keep SynchronizationContext.Current from flowing into a Task.Run delegate?If it flowed, a delegate started from the UI thread would see the UI context as current, and every bare `await` inside it would post its continuation back to the UI thread, undoing the offload that `Task.Run` was for. Keeping `Current` as 'where I am now' prevents that.
- ConfigureAwait(false) drops AsyncLocal<T> values after the await.
- SynchronizationContext.Current flows into Task.Run like any ambient value.
- An async callee's AsyncLocal<T> change is visible to its caller afterwards.
- ExecutionContext decides which thread a continuation runs on.
- ExecutionContext.SuppressFlow() is the per-await equivalent of ConfigureAwait(false).