0
Our legacy ASP.NET Web API endpoint hangs indefinitely whenever we call asynchronous code synchronously using .Result or .Wait(). Why does this happen, and what is the best way to resolve these deadlocks without rewriting the entire call stack?
Understanding SynchronizationContext
In legacy .NET applications, calling .Result blocks the original thread while waiting for the Task to complete. When the Task finishes, it attempts to return to the original SynchronizationContext, which is blocked, resulting in a deadlock.
public async Task<string> GetDataAsync()
{
using (var client = new HttpClient())
{
// ConfigureAwait(false) prevents capturing the current SynchronizationContext
var response = await client.GetAsync("https://api.example.com/data").ConfigureAwait(false);
return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
}
}