Understand and remove sync-over-async deadlocks

A task can be waiting for the same thread that is synchronously waiting for the task. This circular dependency explains why an asynchronous operation sometimes works with await but hangs when its caller reads .Result or calls .Wait().

The usual repair is to keep the call chain asynchronous. First identify the dependency, because slow I/O, a held lock and ThreadPool starvation can produce similar symptoms without the same cause.

Observe the dependency without hanging

Use the .NET 10 SDK. Create a console project in a new directory, then replace Program.cs with the example below.

Plain text
dotnet new console --framework net10.0
dotnet run

Run dotnet run after saving the replacement. No additional packages are required.

The following small context stores callbacks until its owner processes them. Task.Yield makes the continuation wait for that context. The timed wait deliberately stops after 20 milliseconds, so this demonstration terminates. This is a teaching context, not a production message loop or a thread-safe scheduler.

C#
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

var previous = SynchronizationContext.Current;
var context = new QueuedContext();
SynchronizationContext.SetSynchronizationContext(context);
try {
	var pending = ReadAsync();
	Console.WriteLine($"Completed before pump: {pending.IsCompleted}");
	Console.WriteLine($"Queued callbacks: {context.PendingCount}");
	Console.WriteLine($"Timed wait completed: {pending.Wait(20)}");
	context.Drain();
	Console.WriteLine($"Result after pump: {pending.GetAwaiter().GetResult()}");
} finally {
	SynchronizationContext.SetSynchronizationContext(previous);
}

Console.WriteLine($"Awaited result: {await ReadAsync()}");

static async Task<int> ReadAsync() {
	await Task.Yield();
	return 42;
}

/// <summary>Models a single-thread context whose owner must process queued callbacks.</summary>
public sealed class QueuedContext : SynchronizationContext {
	private readonly Queue<Action> _callbacks = new();

	public int PendingCount => _callbacks.Count;

	public override void Post(SendOrPostCallback callback, object? state) => _callbacks.Enqueue(() => callback(state));

	public void Drain() {
		while (_callbacks.TryDequeue(out var callback))
			callback();
	}
}

Expected output:

Plain text
Completed before pump: False
Queued callbacks: 1
Timed wait completed: False
Result after pump: 42
Awaited result: 42

The task cannot finish during the timed wait because its only continuation is still queued. Calling Drain lets that continuation run. Replacing the bounded wait with an indefinite wait would prevent this single thread from reaching Drain. The later GetResult is safe in this particular sample because Drain has already completed the task.

The dependency has the same shape in a UI context whose message loop must execute the continuation. Microsoft's UI deadlock explanation describes that capture-and-wait cycle.

Remove the synchronous boundary

Return Task or Task<T> from the operation and await it through callers. UI event handlers can be async void when their event signature requires it. Ordinary asynchronous methods should return tasks so callers can await completion and observe failures. Do not add a second message pump as an application fix. Reentrant UI callbacks can then execute while the original operation is only partly complete.

For application code that updates controls after an await, retaining the UI context is useful. The companion Windows Forms async guide demonstrates responsive UI work. In reusable library code that does not need that context, ConfigureAwait(false) can avoid capturing it for that particular await. It does not retroactively change awaits inside a method you already called, and it does not guarantee execution on a new thread. The ConfigureAwait FAQ explains these boundaries.

Changing .Result to .GetAwaiter().GetResult() changes how exceptions are surfaced. It does not make the wait asynchronous or remove the dependency. Similarly, wrapping work in Task.Run can bypass one captured-context case, but the caller still blocks. It is not a universal guarantee against locks, reentrancy or scarce-thread problems.

Distinguish the hosting environment

An ordinary console application and ASP.NET Core do not install the classic UI or legacy ASP.NET synchronization context by default. The absence of that particular context does not make blocking free. Under load, many blocked request threads can contribute to ThreadPool starvation . Locks and custom schedulers introduce their own dependencies.

When a genuinely synchronous API must remain, prefer a real synchronous implementation or redesign the boundary that owns it. Assess the caller's context, locks and capacity explicitly before using a blocking bridge. This console sample proves the scheduling dependency. It does not exercise a real Windows Forms, WPF or web-server workload.

Source and further reading

This article revisits the problem discussed in the following original answer. The explanation and examples here are newly written for .NET 10.

Await, and UI, and deadlocks! Oh my! - .NET Blog
It’s been awesome seeing the level of interest developers have had for the Async CTP and how much usage it’s getting.  Of course, with any new technology there are bound to be some hiccups.  One issue I’ve seen arise now multiple times is developers accidentally deadlocking their application by blocking their UI thread, so I […]
https://devblogs.microsoft.com/dotnet/await-and-ui-and-deadlocks-oh-my/
ConfigureAwait FAQ - .NET Blog
.NET added async/await to the languages and libraries over seven years ago. In that time, it’s caught on like wildfire, not only across the .NET ecosystem, but also being replicated in a myriad of other languages and frameworks. It’s also seen a ton of improvements in .NET, in terms of additional language constructs that utilize […]
https://devblogs.microsoft.com/dotnet/configureawait-faq/
Debug ThreadPool Starvation - .NET
A tutorial that walks you through debugging and fixing a ThreadPool starvation issue on .NET Core
https://learn.microsoft.com/en-us/dotnet/core/diagnostics/debug-threadpool-starvation

Author: Herman Schoenfeld