skip to content

In a C# async method, what exactly does await task.ConfigureAwait(false) change about where the following code runs, and when does it change nothing?

level: seniorimportance: must knowfreq 70%

answer

  1. capture, or don't capture
  2. context first, then scheduler
  3. only this one await
  4. already-completed tasks never suspend
  5. null context, nothing to skip

basics

~20 s

ConfigureAwait(false) tells that one await not to capture the current SynchronizationContext or non-default TaskScheduler, so its continuation runs on an unspecified thread, usually the pool. It changes nothing when the task is already complete or when no context exists.

solid answer

~40 s

By default, an `await` on an incomplete `Task` captures `SynchronizationContext.Current` (if it is a real subclass) or else `TaskScheduler.Current` (if it is not `TaskScheduler.Default`), and resumes the method there. `ConfigureAwait(false)` switches that capture off for **that one await**: the continuation runs wherever the system chooses, typically the thread that completed the task or a thread-pool thread. `ConfigureAwait(true)` is the same as writing nothing. It changes nothing in two cases. If the task has already completed, the await does not suspend, so the method carries on synchronously on the same thread and the same context. And if there is no context to capture, as in ASP.NET Core or a console app, there is nothing to skip. It also does not affect later awaits; each await decides for itself.

code

csharp · 34 lines
csharp
using System.Collections.Concurrent;

var ui = new UiContext();
ui.Post(async _ =>
{
    await Task.CompletedTask.ConfigureAwait(false);   // already complete: the method never suspends
    Console.WriteLine($"after a completed task: on UI context = {SynchronizationContext.Current is UiContext}");
    await Task.Delay(50).ConfigureAwait(false);       // suspends, so the setting takes effect
    Console.WriteLine($"after Task.Delay:       on UI context = {SynchronizationContext.Current is UiContext}");
    ui.Complete();
}, null);
ui.Run();

var exclusive = new ConcurrentExclusiveSchedulerPair().ExclusiveScheduler;
await Task.Factory.StartNew(async () =>
{
    await Task.Delay(50);
    Console.WriteLine($"plain await, back on the custom TaskScheduler = {TaskScheduler.Current == exclusive}");
    await Task.Delay(50).ConfigureAwait(false);
    Console.WriteLine($"after ConfigureAwait(false), on it            = {TaskScheduler.Current == exclusive}");
}, CancellationToken.None, TaskCreationOptions.None, exclusive).Unwrap();

sealed class UiContext : SynchronizationContext
{
    private readonly BlockingCollection<(SendOrPostCallback, object?)> _queue = new();
    public override void Post(SendOrPostCallback d, object? state) => _queue.Add((d, state));
    public void Complete() => _queue.CompleteAdding();
    public void Run()
    {
        SetSynchronizationContext(this);
        foreach (var (d, state) in _queue.GetConsumingEnumerable()) d(state);
        SetSynchronizationContext(null);
    }
}

go deeper

for a junior

Remember that a plain await in a UI app comes back to the UI thread, and ConfigureAwait(false) asks it not to.

for a middle

Explain the capture order (SynchronizationContext, then a non-default TaskScheduler) and that the setting applies per await expression.

for a senior

Name the cases where it does nothing: an already-completed task and a context-free host. Show why code after it may still be on the UI thread.

for a principal

Separate library code from app code: the library cannot know its caller's context, so it opts out; app code that needs the UI thread keeps the default.

## The default: capture and come back An `await` on a `Task` or `Task<TResult>` first asks the task's awaiter whether the task is already complete. If it is not, the method suspends and the awaiter registers a **continuation**: the rest of the method. Before registering, the awaiter decides where that continuation should run. The runtime's rule (in `Task.SetContinuationForAwait`) is: 1. If `SynchronizationContext.Current` is non-null **and** is a subclass rather than the plain base `SynchronizationContext` type, capture it and later call its `Post` method. 2. Otherwise, if the current `TaskScheduler` (the scheduler of the task now running) is **not** `TaskScheduler.Default`, capture it and queue the continuation to it. 3. Otherwise, capture nothing; the continuation runs on the thread pool or inline on the thread that completed the task. So a WPF or Windows Forms UI thread resumes on the UI thread, a task started on a custom scheduler (for example the `ExclusiveScheduler` of a `ConcurrentExclusiveSchedulerPair`) resumes on that scheduler, and code with neither resumes "anywhere". ## What ConfigureAwait(false) changes `task.ConfigureAwait(continueOnCapturedContext: false)` returns a `ConfiguredTaskAwaitable` whose awaiter skips steps 1 and 2. The ConfigureAwaitOptions documentation in the runtime puts it plainly: without the capture option, "the thread on which the continuation is invoked is unspecified and left up to the determination of the system." In practice that is a thread-pool thread or the thread that completed the operation. - `ConfigureAwait(true)` is identical to a bare `await`; the CA2007 documentation calls it a way to state intent. - The setting belongs to **one await expression**. The next `await` in the same method decides afresh. After a `ConfigureAwait(false)` that really suspended, though, the method is usually on a pool thread with no context, so later awaits have nothing to capture anyway. - `ValueTask` and `ValueTask<TResult>` have `ConfigureAwait(bool)` methods with the same meaning, and extension methods give `IAsyncEnumerable<T>` (for `await foreach`) and `IAsyncDisposable` (for `await using`) one too. - It never affects **ExecutionContext**: ambient values such as `AsyncLocal<T>` flow across every await regardless. ## When it changes nothing | Situation | Effect of `ConfigureAwait(false)` | |---|---| | The awaited task is already complete | none: no suspension, execution continues on the same thread and context | | No `SynchronizationContext` and the default scheduler (ASP.NET Core, console, thread pool) | none: there was nothing to capture | | UI thread, task still running | continuation runs off the UI thread | | Inside a task on a custom `TaskScheduler` | continuation leaves that scheduler | The first row is the one that surprises people. A cache lookup that returns `Task.FromResult(value)` or a buffered read that finished synchronously never suspends, so `await cached.ConfigureAwait(false)` leaves you **on the UI thread**. Code that assumes "after ConfigureAwait(false) I am on the pool, so heavy CPU work here is fine" can still freeze the UI. If the goal is to get off the current thread, use `Task.Run` for the CPU work, or, from .NET 8, `ConfigureAwaitOptions.ForceYielding`. ## Consequences for code after the await - Code after `ConfigureAwait(false)` must not touch UI controls: from a pool thread that is a cross-thread access, which WPF rejects with an `InvalidOperationException` and Windows Forms does not support. - `SynchronizationContext.Current` is `null` on the pool thread, so a nested call that awaits without `ConfigureAwait(false)` captures nothing and cannot post back to a blocked UI thread. That is why it defuses the `.Result` deadlock for awaits that run after it; awaits that suspend before it, while the UI context is current, still capture. - It saves a post and a queue hop per await in UI apps, a small performance gain for library code that does not need the UI thread. ## Who should write it - **Library code** that does not touch UI or any context-specific state: Microsoft's guidance for library authors is to use `ConfigureAwait(false)` on every await unless the code needs the captured context. - **UI application code**, such as event handlers that update controls after the await: leave the default, because coming back to the UI thread is the point. - **ASP.NET Core application code**: it has no effect there, because there is no context; writing it is harmless noise. Library code should still use it, because the library cannot know whether its next caller is a UI app. The interview answer turns on two words: *capture* and *suspend*. `ConfigureAwait(false)` is a decision about capture, and capture only matters when the await actually suspends.

  • If the first await in a C# method uses ConfigureAwait(false), do the later awaits in that method still need it?
    Strictly, each await decides for itself. If the first one really suspended, the method usually resumes on a pool thread with no `SynchronizationContext`, so later bare awaits capture nothing. But if that first task was already complete, the method is still on the original context, and a later bare await captures it. That is why library guidance is to put it on every await.
  • Why does the awaiter ignore a SynchronizationContext.Current that is the base SynchronizationContext class itself?
    The base class's `Post` just queues to the thread pool, so it is treated as equivalent to having no context. The runtime skips it to avoid needless posting, and so that publishing the default context does not hide a non-default `TaskScheduler` that should be used instead.

  • ConfigureAwait(false) makes the awaited operation itself run on a background thread.
  • After ConfigureAwait(false) you are always on a thread-pool thread.
  • ConfigureAwait(false) on the first await applies to the whole method.
  • ConfigureAwait(false) stops AsyncLocal values from flowing to the continuation.
  • ConfigureAwait(true) forces a thread switch back even when no context exists.