skip to content

In C#, how do .Result, .Wait() and GetAwaiter().GetResult() differ when blocking on a Task, and does any of them avoid the UI deadlock?

level: middleimportance: should knowfreq 60%

answer

  1. same blocking, different exception shape
  2. AggregateException vs the original
  3. what await would have thrown
  4. a thread with no context
  5. the UI still stops repainting

basics

~20 s

.Result and .Wait() wrap a failure in AggregateException, while GetAwaiter().GetResult() throws the original exception as await would. All three block the calling thread, so none of them avoids the UI deadlock; only not blocking does.

solid answer

~40 s

All three are sync-over-async: they park the calling thread until the task completes. They differ in how a failure surfaces. `Task<T>.Result` and `Task.Wait()` throw an `AggregateException` whose `InnerExceptions` hold the task's exceptions, so a caller catching `InvalidOperationException` misses it. `GetAwaiter().GetResult()` throws the first exception unwrapped, a cancelled task as `TaskCanceledException`, exactly as `await` would; that is why it is the usual choice when blocking is unavoidable. None avoids the deadlock, because the UI thread is still blocked while the continuation is posted to it. If you must block on code you cannot change, `Task.Run(() => LoadAsync()).Result` starts the method on a thread-pool thread, where no context is captured, so it completes; the UI thread is still frozen until it does.

code

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

var ui = new UiContext();
ui.Post(_ =>
{
    try { _ = ReportClient.FailAsync().Result; }
    catch (Exception ex) { Console.WriteLine($".Result:                  {ex.GetType().Name} wrapping {ex.InnerException?.GetType().Name}"); }

    try { _ = ReportClient.FailAsync().GetAwaiter().GetResult(); }
    catch (Exception ex) { Console.WriteLine($"GetAwaiter().GetResult(): {ex.GetType().Name}"); }

    // LoadAsync awaits without ConfigureAwait(false); Task.Run starts it where no context exists.
    string report = Task.Run(() => ReportClient.LoadAsync()).Result;
    Console.WriteLine($"Task.Run(...).Result:     {report}");
    ui.Complete();
}, null);
ui.Run();

static class ReportClient
{
    public static async Task<string> LoadAsync() { await Task.Delay(50); return "report loaded"; }
    public static async Task<string> FailAsync()
    {
        await Task.Delay(50).ConfigureAwait(false);
        throw new InvalidOperationException("report service unavailable");
    }
}

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);
    }
}

go deeper

for a junior

Recall that .Result and .Wait() block the thread, and that awaiting is the normal way to get a task's value.

for a middle

Explain the exception difference: AggregateException from .Result and .Wait(), the original exception from GetAwaiter().GetResult(), and why all three still block.

for a senior

Pick a mitigation for a synchronous interface over async code: ConfigureAwait(false) if you own it, Task.Run offloading if not, with each one's cost stated.

for a principal

Decide where sync-over-async may exist at all, for example only at a legacy boundary, and how to test that boundary from a UI thread and under load.

## Three ways to block on a Task Code that must produce a value synchronously from an asynchronous method has three common spellings: - `task.Result`, on a `Task<TResult>`: blocks until completion, then returns the value. - `task.Wait()`, on any `Task`: blocks until completion and returns nothing. Overloads such as `Wait(int millisecondsTimeout)` and `Wait(TimeSpan)` return `false` on timeout instead of blocking forever. - `task.GetAwaiter().GetResult()`: asks the task's awaiter, the same object the compiler uses for `await`, for its result, and blocks if the task is not finished. This is **sync-over-async**. Each of them occupies the calling thread for the whole operation; no thread is released while the I/O is in flight. ## How a failure surfaces | Call | Faulted task | Cancelled task | |---|---|---| | `.Result` | `AggregateException`, inner = the original | `AggregateException`, inner = `TaskCanceledException` | | `.Wait()` | `AggregateException`, inner = the original | `AggregateException`, inner = `TaskCanceledException` | | `.GetAwaiter().GetResult()` | the original exception | `TaskCanceledException` | | `await` | the original exception | `TaskCanceledException` | The wrapping matters in practice: 1. A `catch (InvalidOperationException)` written around `.Result` never fires, because the exception is an `AggregateException`. 2. Logs show `AggregateException: One or more errors occurred` with the real cause one level down. 3. `GetAwaiter().GetResult()` preserves the original exception and its stack trace, so the same `catch` blocks work whether the caller awaits or blocks. When a task holds several exceptions (for example from `Task.WhenAll`), `AggregateException` carries all of them and `GetResult()` throws only the first; the details of combining tasks are covered with task combinators. A `.Result` read on a task that has **already completed** successfully does not block and is fine, which is the common pattern after awaiting `Task.WhenAll`. ## Why none of them avoids the deadlock The UI deadlock has nothing to do with *how* you block, only with *which thread* blocks. When the click handler blocks the UI thread and the async method's await has captured the UI `SynchronizationContext`, the continuation is queued to the UI thread, which is parked. `GetAwaiter().GetResult()` parks it exactly as `.Result` does. The fashion of writing `GetAwaiter().GetResult()` "to avoid deadlocks" is a myth; it only avoids the `AggregateException` wrapper. ## Timeouts are not a fix A tempting patch is `if (!task.Wait(TimeSpan.FromSeconds(5))) { ShowError(); }`. On a UI thread it turns a permanent hang into a five-second freeze followed by an error, every time, because the continuation still cannot run while the thread waits. Worse, the timeout does not stop anything: - the asynchronous operation keeps running after `Wait` returns `false`; - its continuation stays queued to the UI context and runs later, once the handler returns, possibly updating state the user has already moved past; - a failure inside that late continuation surfaces nowhere unless something observes the task. A timeout is useful for proving the deadlock in a test, as the snippet in this lesson does; it is not a production fix. ## When blocking cannot be avoided Sometimes a synchronous interface must be implemented on top of an asynchronous API. Microsoft's guidance on synchronous wrappers lists the mitigations: - **If you own the async code**, use `ConfigureAwait(false)` on every await, so no continuation needs the blocked thread. - **If you do not own it**, offload it: `Task.Run(() => client.LoadAsync()).GetAwaiter().GetResult()`. The delegate starts on a thread-pool thread, where `SynchronizationContext.Current` is `null`, so the awaits inside capture nothing and complete on the pool. - **Test the wrapper** from a UI thread, from the thread pool under load and from a console app, because it can work in one and hang in another. The offload has costs. The calling thread is still blocked, so a desktop window still stops repainting for the duration; a thread-pool thread is now involved as well; and if the async code needs the original thread (for example it touches UI controls), it now runs off the UI thread and fails there instead. On a server, blocking pool threads this way contributes to thread-pool starvation, which the ASP.NET Core material covers. ## The ranking 1. Do not block: make the caller `async` and `await`. 2. If you must block on code you own, make that code context-free with `ConfigureAwait(false)` and block with `GetAwaiter().GetResult()` for clean exceptions. 3. If you must block on code you do not own, offload it with `Task.Run` and accept the cost. A candidate who says "use `GetAwaiter().GetResult()` instead of `.Result` and the deadlock goes away" has confused exception shape with scheduling.

  • Why can a C# console app call .Result on an async method without deadlocking, yet still be a bad model for the desktop app that uses the same code?
    A console app has no `SynchronizationContext`, so continuations run on the thread pool and the blocked main thread is released. A desktop UI thread has a single-threaded context, so the same continuation is queued to the blocked thread. Code tested only from a console can hide the deadlock.
  • In C#, is it safe to read .Result after await Task.WhenAll(first, second)?
    Yes. After the `await`, both tasks have completed, so `first.Result` returns immediately without blocking and cannot deadlock. If either had failed, the `await` would already have thrown. Reading `.Result` here is just reading a stored value.

  • GetAwaiter().GetResult() avoids the UI deadlock that .Result causes.
  • .Wait() is safe because it returns nothing, unlike .Result.
  • Catching InvalidOperationException around .Result catches the task's InvalidOperationException.
  • Task.Run(...).Result keeps a desktop UI responsive while it waits.
  • Reading .Result on an already-completed task can deadlock.