skip to content

In C#, why does .Result on an async method freeze a desktop app's button handler but work fine inside an ASP.NET Core web API?

level: middleimportance: must knowfreq 80%

answer

  1. who runs the code after await
  2. one UI thread, one message queue
  3. the continuation is posted back
  4. blocked thread cannot drain its own queue
  5. no context in ASP.NET Core

basics

~20 s

The library's await captures the UI SynchronizationContext and posts its continuation back to the UI thread, but that thread is blocked inside .Result waiting for it. ASP.NET Core has no SynchronizationContext, so the continuation runs on a thread-pool thread instead.

solid answer

~50 s

When an `await` meets an incomplete task, it captures `SynchronizationContext.Current`, and when the task finishes it posts the rest of the method back to that context. A WPF or Windows Forms UI thread installs a context whose `Post` queues work onto that single UI thread. The button handler calls `LoadAsync().Result`, so the UI thread blocks until the task completes, but the task cannot complete until its continuation runs on the UI thread. Neither side can move, and the window stops repainting. ASP.NET Core installs no `SynchronizationContext`, so the same continuation runs on a thread-pool thread and `.Result` merely wastes the blocked thread. The fix is to make the handler `async` and `await` the call; `ConfigureAwait(false)` inside the library also removes this deadlock, as long as every await that suspends while the UI context is current uses it.

code

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

var ui = new UiContext();
ui.Post(_ => OnRefreshClick(), null);   // a simulated button click on the UI thread
ui.Run();

void OnRefreshClick()
{
    Task<string> plain = ReportClient.LoadAsync(continueOnCapturedContext: true);
    Console.WriteLine(plain.Wait(2000) ? plain.Result : "plain await: deadlocked, gave up after 2 s");

    Task<string> configured = ReportClient.LoadAsync(continueOnCapturedContext: false);
    Console.WriteLine(configured.Wait(2000) ? "ConfigureAwait(false): " + configured.Result : "deadlocked");
    ui.Complete();
}

static class ReportClient
{
    public static async Task<string> LoadAsync(bool continueOnCapturedContext)
    {
        await Task.Delay(100).ConfigureAwait(continueOnCapturedContext);
        return "report loaded";
    }
}

sealed class UiContext : SynchronizationContext   // one thread drains a queue, like a UI message loop
{
    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);
    }
}

go deeper

for a junior

Recall that blocking on a task with .Result from a UI thread can freeze the app, and that the safe habit is to make the event handler async and await the call.

for a middle

Walk through the cycle: await captures the UI SynchronizationContext, the UI thread blocks in .Result, the continuation is queued to that blocked thread. Contrast it with ASP.NET Core's missing context.

for a senior

Show you can find this in a hang dump: a UI thread blocked inside .Result or Wait under a click handler. Explain why one missed ConfigureAwait(false) in a callee is enough to keep the bug alive.

for a principal

Frame it as a library contract: shared code must not assume its caller's context, must not expose sync-over-async wrappers, and should be tested from a single-threaded context.

## The scenario A desktop app has a **Refresh** button. Its click handler calls a shared library's `Task<string> LoadReportAsync()` and, because the handler is an ordinary `void` method, reads the result with `.Result`. The window freezes for good: no repaint, no further clicks. The same library is used inside an ASP.NET Core web API, where a controller also calls `.Result` (not a good idea there either), and nothing hangs. Same code, two outcomes. The difference is the **SynchronizationContext** of the calling thread. ## What await captures `SynchronizationContext` is a .NET abstraction for *where code should run*. Its key member is `Post`, which queues a delegate to the target environment. - **WPF** installs `DispatcherSynchronizationContext`, whose `Post` calls `Dispatcher.BeginInvoke`. - **Windows Forms** installs `WindowsFormsSynchronizationContext`, whose `Post` calls `Control.BeginInvoke`. - **Console apps and ASP.NET Core** install none, so `SynchronizationContext.Current` is `null`. When an `await` on a `Task` finds the task still incomplete, the task awaiter reads `SynchronizationContext.Current`. If there is one (and it is not the plain base `SynchronizationContext` class), the awaiter captures it and, when the task completes, **posts** the rest of the async method to it. With no context, it checks for a non-default `TaskScheduler`; with neither, the continuation runs on a thread-pool thread or inline on the thread that completed the task. This is how `await` "comes back" to the UI thread so that code after it can touch controls. ## How the deadlock forms 1. The UI thread runs the click handler and calls `LoadReportAsync()`. 2. The library runs synchronously until `await httpCall`, which is not finished, so the await captures the UI context and the method returns an incomplete `Task<string>`. 3. The handler calls `.Result`, which **blocks the UI thread** until that task completes. 4. The HTTP response arrives. The continuation (the rest of `LoadReportAsync`) is posted to the UI context, which means it is queued for the UI thread. 5. The UI thread is blocked in `.Result` and never returns to its message loop, so the queued continuation never runs, so the task never completes. No lock is held; the cycle is the UI thread waiting for a task that waits for the UI thread. `.Wait()` and `GetAwaiter().GetResult()` block the same way, so swapping one for another changes nothing. ## Why the web API survives ASP.NET Core does not install a `SynchronizationContext`. At step 4 the continuation has no context to return to and simply runs on a thread-pool thread, completes the task, and releases the request thread blocked in `.Result`. The call "works", but it holds a thread idle for the duration of the I/O; under load that is the road to thread-pool starvation, which belongs to the ASP.NET Core material, not to this deadlock. Classic ASP.NET on .NET Framework did have a request context, and Microsoft's documentation warns that the same `.Result` can deadlock there too: the behaviour follows the *environment*, not the library. | Caller | `SynchronizationContext.Current` | Continuation runs on | `.Result` outcome | |---|---|---|---| | WPF / Windows Forms UI thread | UI context (one thread) | the UI thread, via its queue | deadlock | | ASP.NET Core request | `null` | a thread-pool thread | completes, thread wasted | | Console app | `null` | a thread-pool thread | completes | ## The fixes, in order of preference - **Async all the way.** Make the handler `async void OnRefreshClick(object sender, EventArgs e)` and `await LoadReportAsync()`. The UI thread returns to its message loop during the I/O, and the continuation comes back to it as intended, so the code after the await can update the screen. Event handlers are the accepted place for `async void`; the rules for it are covered with task-based methods. - **`ConfigureAwait(false)` in the library.** `await httpCall.ConfigureAwait(false)` tells the awaiter not to capture the context, so the continuation runs on the thread pool and completes the task even while the UI thread is blocked. It only helps if **every** await that suspends while the UI context is still current uses it, including awaits inside methods the library calls before its first real suspension. One plain await in that stretch is enough to post back to the blocked UI thread. - **Do not ship a synchronous wrapper** like `LoadReport() => LoadReportAsync().Result` from a library. Microsoft's guidance on synchronous wrappers says to leave the decision to block to the caller, who knows the threading environment. The fix the interview wants first is the first one: the deadlock is a symptom of blocking on asynchronous work from a thread that the work needs.

  • Why does the deadlock still happen if the library's top-level method uses ConfigureAwait(false) but calls a helper whose own await does not?
    The helper runs synchronously on the UI thread until its first incomplete await. If that await has no `ConfigureAwait(false)`, it captures the UI context and later posts its continuation there. The outer method's setting only applies to the outer await. Every await that can suspend while the UI context is current needs the setting.
  • Does the same .Result call deadlock in a C# console app?
    No. A console app has no `SynchronizationContext`, so `SynchronizationContext.Current` is `null` and the continuation runs on a thread-pool thread, completes the task and releases the blocked main thread. That is why sync-over-async code can pass console tests and still hang in a desktop app.
  • Would calling the library through Task.Run(...).Result avoid the freeze?
    It avoids the deadlock, because the async method starts on a thread-pool thread with no context to capture. It does not avoid the freeze: the UI thread is still blocked for the whole operation and cannot repaint. It is a last resort for code you cannot change, not a fix.

A shop with one cashier: the cashier orders a part and then stands at the counter refusing to move until it arrives, but the courier will only hand the part to the cashier at the back door. The courier waits at the door, the cashier waits at the counter, and the shop is stuck.

  • The deadlock is caused by a lock inside the library.
  • Replacing .Result with GetAwaiter().GetResult() prevents the deadlock.
  • await always resumes on the thread pool, whatever thread started it.
  • ASP.NET Core does not deadlock because it uses a smarter SynchronizationContext.
  • ConfigureAwait(false) on the outermost await alone is always enough.