
Blocking on .Result Hurts ASP.NET Core Even Without a Deadlock
- كاتب موثّق
- .NET 10
محتويات المقال
ToLocal, because the interface it implements was written years ago. Inside, one line does the bridging: rates.GetRateAsync(currency).GetAwaiter().GetResult(). In review, someone asks about deadlocks, and the answer is correct: ASP.NET Core has no synchronization context, so there's nothing to deadlock on. Tests pass, normal traffic is fine. Then, after each morning deploy, requests that usually take 200 ms take seconds, health checks time out, and the orchestrator starts restarting instances. CPU stays low, and there's no exception to look at.
The common misconception
.Result, .Wait() and GetAwaiter().GetResult() are safe there, just a little wasteful.
await must resume on the very thread that's blocked waiting for it. That can't happen in ASP.NET Core. The code returns the right value, and at low traffic it's as fast as the async version. One thread waiting 200 ms sounds like a rounding error.
What actually happens
A blocked thread is a lost thread
await, the thread goes back to the pool while the HTTP call is in flight and serves other requests. With , it stays parked until the call returns, doing nothing. Fifty concurrent requests to a 200 ms call need about fifty threads instead of a handful. The best practices page is direct about the result: many blocking calls "lead to Thread Pool starvation and degraded response times".
The pool adds threads slowly, by design
The work that releases them waits in the same queue
await inside GetRateAsync, its . That code needs a pool thread as well, and it's queued behind incoming requests. Every new thread the pool adds may pick up a new request and block too. It's a deadlock in slow motion that only ends when the pool has added enough threads. That's .
What it looked like in a test
Async: p95 latency 219 ms, 8 to 9 pool threads, a /healthendpoint answered in about 1 ms.Blocking: the first requests took up to 7.3 seconds, and /health, which returns a constant, took 7.3 seconds too. The pool grew to 56 threads before latency settled.GetAwaiter().GetResult()behaved the same.One run in four: 50 threads blocked, work still queued, and nothing completed for 56 seconds. The test machine was close to its memory limit, where the docs say injection slows. With 200 clients, the blocking version finished nothing within the two-minute timeout.
The fix: async all the way up
var builder = WebApplication.CreateBuilder(args);builder.Services.AddHttpClient<RatesClient>();builder.Services.AddScoped<PriceCalculator>();var app = builder.Build();app.MapGet("/quote", (decimal amount, string currency, PriceCalculator calc) => calc.ToLocal(amount, currency));app.Run();public sealed class PriceCalculator(RatesClient rates){ public decimal ToLocal(decimal amount, string currency) { // No deadlock, but this pool thread is parked until the call returns var rate = rates.GetRateAsync(currency).GetAwaiter().GetResult(); return amount * rate; }}var builder = WebApplication.CreateBuilder(args);builder.Services.AddHttpClient<RatesClient>();builder.Services.AddScoped<PriceCalculator>();var app = builder.Build();app.MapGet("/quote", (decimal amount, string currency, PriceCalculator calc, CancellationToken ct) => calc.ToLocalAsync(amount, currency, ct));app.Run();public sealed class PriceCalculator(RatesClient rates){ public async Task<decimal> ToLocalAsync(decimal amount, string currency, CancellationToken ct) { // The thread goes back to the pool while the HTTP call is in flight var rate = await rates.GetRateAsync(currency, ct); return amount * rate; }}ToLocal becomes ToLocalAsync, its interface returns Task<decimal>, and every caller awaits it. That's the real cost of the fix, and it's why blocking calls survive in old interfaces.
SynchronizationContext, so .Result is safe | |
GetAwaiter().GetResult() is the safe way to block | AggregateException |
Task.Run(...).Result moves the blocking elsewhere | |
SetMinThreads fixes it |
How to apply it in your project
Find the blocking calls Search for .Result,.Wait(),GetAwaiter().GetResult()andTask.WaitAll. Turn on analyzer rule CA1849, which is off by default in .NET 10; it flags these calls inside methods that return aTask. Calls in synchronous methods still need the text search.Make the chain async, starting at the bottom Change the method that blocks to return a Task, await it, and pass aCancellationToken. Then fix each caller up to the endpoint. Where an interface forces a synchronous signature, add an async version and move callers to it.Replace the framework calls that block Some blocking hides in framework calls. The docs list Request.Formand a synchronousReadToEndon the request body as sync over async; useawait Request.ReadFormAsync()andReadToEndAsyncinstead.Load test a cold process Starvation hides at low traffic and in warm processes. Start a fresh instance, send many concurrent requests right away, and watch latency and thread count with dotnet-counters.
Key takeaways
No SynchronizationContextmeans no classic deadlock, not safe blocking: every blocked call holds a pool thread.The continuation that would release a blocked thread needs a pool thread too, so blocking under load starves the pool. The pool grows gradually and more slowly under memory pressure; until it catches up, every request waits, even trivial ones. GetAwaiter().GetResult(),Task.Run(...).ResultandSetMinThreadsdon't fix it; awaiting all the way up does.Look for a climbing thread count with low CPU, and find the blocked frames with dotnet-stack.
📚 المصادر
ASP.NET Core Best Practices: Avoid blocking calls — Microsoft Learn Debug ThreadPool starvation — .NET, Microsoft Learn The managed thread pool — .NET, Microsoft Learn Threading config settings: thread injection in response to blocking — Microsoft Learn CA1849: Call async methods when in an async method — Microsoft Learn
التعليقات (0)