Volume 1 · Chapter 5 — Modern C# and .NET Foundations
Async/Await Internals
5.1 Introduction
Enterprise applications spend most of their time waiting - on databases, HTTP calls, files, and message queues. Asynchronous programming lets an application do other useful work during those waits instead of blocking a thread. The single most important thing to understand is thatasync/awaitis aboutnot blocking threads while waiting, not about running work faster or in parallel. For I/O-bound work, a thread that would sit idle waiting for a response is released back to the pool to serve other requests - which is how a modest number of threads handles thousands of concurrent connections.
5.2 Synchronous vs Asynchronous
sequenceDiagram autonumber participant Req as Request participant T as Pool Thread participant DB as Database (async I/O) Note over Req,DB: Synchronous Req->>T: handler runs T->>DB: query (thread BLOCKS waiting) DB-->>T: result Note over Req,DB: Asynchronous Req->>T: handler runs T->>DB: await query T-->>Req: thread released to pool (not blocked) DB-->>T: completes -> continuation resumes (any pool thread)
5.3 Tasks and What await Does
ATaskrepresents an asynchronous operation that may complete in the future - it does not necessarily mean a dedicated thread; for I/O the OS handles the waiting while application threads stay free. The compiler rewrites anasyncmethod into a state machine: at eachawait, if the operation has not completed, the method returns to its caller and registers a continuation - the rest of the method - to run when the operation completes. No thread is blocked in between.
public async Task<Customer> GetCustomerAsync(Guid id, CancellationToken ct)
{
var customer = await _repository.GetAsync(id, ct); // suspends; thread released
var orders = await _orders.GetForAsync(id, ct); // suspends again
return Map(customer, orders);
}
5.4 SynchronizationContext and ConfigureAwait
By defaultawaitcaptures the currentSynchronizationContextso the continuation resumes on the original context - essential in UI apps where you must return to the UI thread. ASP.NET Core has no synchronization context, so this capture is unnecessary there. In reusable library code,ConfigureAwait(false)avoids capturing the context, reducing overhead and a class of deadlocks.
public async Task<string> FetchAsync(Uri uri)
{
using var resp = await _http.GetAsync(uri).ConfigureAwait(false); // don't capture context
return await resp.Content.ReadAsStringAsync().ConfigureAwait(false);
}
5.5 ValueTask, Cancellation, and Anti-Patterns
ValueTaskavoids allocating aTaskwhen an operation frequently completes synchronously (a cache hit), but has stricter usage rules (await once, never concurrently).CancellationTokenenables cooperative cancellation so abandoned work stops. The common anti-patterns are blocking on async (.Result/.Wait()),async void, creating unnecessary tasks, and ignoring cancellation.
// ValueTask for a mostly-synchronous cache read; propagate CancellationToken.
public ValueTask<int> GetCachedAsync(string key, CancellationToken ct)
=> _cache.TryGetValue(key, out int v) ? new ValueTask<int>(v) : LoadAsync(key, ct);
public async Task ProcessAsync(CancellationToken ct)
{
while (!ct.IsCancellationRequested)
await ProcessItemAsync(ct); // stops promptly when cancelled
}
Does async/await create a new thread?
No.async/awaitdoes not automatically create or use an extra thread - that is the most common misconception. Its purpose is to avoidblockinga thread while waiting for an asynchronous operation. For I/O-bound work (database, HTTP, file), the actual waiting is handled by the operating system’s asynchronous I/O; there is no thread sitting and waiting. When youawaitsuch an operation, the current thread is released back to the thread pool to do other work, and when the operation completes, the continuation (the rest of your method) is scheduled to run on an available pool thread. So instead of consuming a thread per in-flight operation, a small number of threads can serve many concurrent operations, which is the scalability benefit. The exception is CPU-bound work: if you explicitly offload computation withTask.Run, that does use a pool thread to run the computation - but that is offloading, not whatawaiton I/O does. The key point is that async is about non-blocking waiting for scalability, not about spawning threads or making a single operation faster.
Why does blocking on async code with .Result or .Wait() cause deadlocks?
On a thread that has a synchronization context (classic UI, legacy ASP.NET), the awaited continuation is scheduled back onto that specific context. If you call.Resultor.Wait(), you block that very thread waiting for the Task to complete - but the Task cannot complete because its continuation needs the blocked thread to run, so each waits for the other forever: a deadlock. ASP.NET Core has no synchronization context so it deadlocks less often, but sync-over-async still causes serious harm there: it blocks a thread-pool thread that could be serving requests, and under load this leads to thread-pool starvation (requests queue up, throughput collapses, even though CPU is low), because the pool injects new threads only slowly. The correct approach is to be async all the way down - never block on a Task - and to useConfigureAwait(false)in libraries, which removes the context capture that triggers the classic deadlock. In short, blocking on async couples a thread to a continuation that needs it, deadlocking with a context and starving the pool without one.
What does ConfigureAwait(false) do and where should you use it?
It tellsawaitnot to capture and resume on the current synchronization context, so the continuation runs on any available thread-pool thread instead of being marshaled back to the original context. Use it in general-purpose library code, where you neither know nor care about the caller’s context: it avoids the overhead of the context switch and prevents the sync-over-async deadlock that occurs when a captured context is blocked. You omit it in UI event handlers, where youdoneed to resume on the UI thread to touch controls safely. In ASP.NET Core application code it is largely a no-op because there is no synchronization context to capture, though it remains good hygiene in shared libraries that might also run in a UI context. So the rule of thumb is: useConfigureAwait(false)throughout reusable library code, don’t use it where you must return to a specific context (UI), and don’t worry about it much in ASP.NET Core app code where there is no context anyway.
Why is async void dangerous, and when is it acceptable?
Anasync voidmethod returns nothing awaitable, which has serious consequences: the caller cannot await its completion or know when it finishes, and - critically - it cannot catch exceptions from it. An unhandled exception in anasync voidmethod does not propagate to a caller’s try/catch; it is raised on the synchronization context and typically crashes the process. It also makes the method impossible to compose or test reliably, since there is no Task to await or inspect. The only legitimate use is an event handler, whose signature is required to returnvoid- and even there you should wrap the body in a try/catch to handle exceptions locally. Everywhere else, returnTaskorTask<T>so that completion and failures are observable and the method can be awaited, composed, and tested. Soasync voidis acceptable only for event handlers (with internal exception handling) and should be avoided in all other code.
An API's throughput collapses under load and requests queue up, though CPU is low. What is happening and how do you fix it?
Low CPU with collapsing throughput and queuing requests is the classic signature of thread-pool starvation, almost always caused by sync-over-async: somewhere on the hot path, code blocks a pool thread with.Result,.Wait(), or a synchronous I/O call. As load rises, threads get stuck waiting, the pool injects replacements only slowly (a few per second), and the backlog grows faster than threads become available, so throughput craters even though the CPUs are idle. I’d confirm withdotnet-counters(thread-pool queue length climbing, thread count pinned) and a dump showing many threads blocked inWaitor synchronous I/O. The fix is to make the offending path fully async end to end and remove any synchronous I/O - be async all the way down. As an immediate mitigation you can raise the minimum thread count to absorb the blocking, but that treats the symptom, not the cause. The durable fix is eliminating sync-over-async, and I’d prevent recurrence by banning.Result/.Wait()in code review and adding a Roslyn analyzer to catch it. The lesson is that a single blocking call on a hot path can destroy the scalability that async was supposed to provide.
5.6 Production Scenario
A payments API handles thousands of concurrent transactions with fully async handlers - database, fraud, and ledger calls all use native async APIs and propagate a linkedCancellationTokenwith a timeout. A load test once exposed a collapse under peak: a logging helper used a synchronous file write that blocked pool threads. Replacing it with async logging and adding an analyzer to ban.Resultrestored linear scaling, letting the service handle far more requests on the same thread budget.
Chapter Revision Notes
- Async is about not blocking threads during I/O, not about parallelism or new threads.
- await turns methods into state machines; the thread is released at each suspension.
- Never block on async (.Result/.Wait) - deadlocks with a context, starves the pool without one.
- Use ConfigureAwait(false) in libraries; propagate CancellationToken; avoid async void.
- ValueTask reduces allocations for synchronously-completing hot paths (with usage rules).