Understanding async/await
async/await lets a thread do other work while an I/O call (database, HTTP, disk) is waiting, instead of sitting blocked. Every modern .NET API is async, so understanding what await really does, and the deadlock and async void traps, is essential.
33.1 Why is it used?
- A blocked thread does no work but still counts as busy; the thread pool runs out and requests queue up (thread pool starvation).
- await frees the thread during the wait, so the same few threads serve many more requests: scalability.
- In desktop/UI apps it keeps the UI responsive while work is in progress.
- Demo: 100 requests with Thread.Sleep(1000) took 11175 ms; with await Task.Delay(1000) they took 1038 ms.
33.2 The bug: a blocking wait
- Task.Run sends each of 100 requests to the thread pool, as ASP.NET Core does.
- HandleRequest blocks its thread for 1 second with Thread.Sleep (standing in for a DB call).
using System.Diagnostics; var sw = Stopwatch.StartNew();var requests = Enumerable.Range(1, 100) .Select(_ => Task.Run(HandleRequest));await Task.WhenAll(requests);long ms = sw.ElapsedMilliseconds; Console.WriteLine($"100 requests: {ms} ms"); void HandleRequest(){ Thread.Sleep(1000); // DB call ka wait}$ dotnet run Blocking.cs100 requests: 11175 ms- Step 1
1.100 requests sent to the thread pool
- Step 2
2.Each calls Thread.Sleep(1000): thread idle but busy
- Step 3
3.Pool starts with ~1 thread per core (8 here)
- Step 4
4.New threads are added slowly
- Step 5
5.Remaining requests wait in a queue: ~11 s total
100 x 1 s on ~8 threads is about 11 s
33.3 Fix: await, don't block
- HandleRequestAsync returns async Task and uses await Task.Delay(1000), an asynchronous wait like a real DB/HTTP call.
- No thread is blocked during the wait, so all 100 finish in about 1 second.
using System.Diagnostics; var sw = Stopwatch.StartNew();var requests = Enumerable.Range(1, 100) .Select(_ => Task.Run(HandleRequestAsync));await Task.WhenAll(requests);long ms = sw.ElapsedMilliseconds; Console.WriteLine($"100 requests: {ms} ms"); async Task HandleRequestAsync(){ await Task.Delay(1000); // DB call ka wait}$ dotnet run NonBlocking.cs100 requests: 1038 ms33.4 Task and await: how the thread is freed
- Task<T> is a promise that a result will arrive later.
- await does not block: it pauses the method at that point and returns the thread to the pool.
- The rest of the method (the continuation) runs later on any free thread: thread 2 before, thread 5 after.
int Id() => Environment.CurrentManagedThreadId; Console.WriteLine($"Before await: thread {Id()}");decimal price = await GetPriceAsync(1042);Console.WriteLine($"After await: thread {Id()}");Console.WriteLine($"Price: {price}"); async Task<decimal> GetPriceAsync(int productId){ await Task.Delay(500); // HTTP call ka wait return 1899m;}$ dotnet run AwaitThread.csBefore await: thread 2After await: thread 5Price: 1899- Step 1
1.Async call starts and returns an incomplete Task
- Step 2
2.await pauses the method, thread goes back to the pool
- Step 3
3.Thread serves other requests meanwhile
- Step 4
4.I/O completes, the OS signals .NET
- Step 5
5.Continuation runs on a free thread
No thread is blocked during the wait
33.5 I/O bound vs CPU bound
| Point | I/O bound | CPU bound |
|---|---|---|
| Waiting on | Network, disk, database | The CPU doing calculations |
| Example | DB query, HTTP call, file read | Counting primes, image resize |
| What to do | Just await the async API | Task.Run to move it to a background thread |
| Benefit | Thread free during the wait | UI does not freeze |
| In ASP.NET Core | await directly | Do not wrap I/O in Task.Run |
int count = await Task.Run( () => CountPrimes(2_000_000));Console.WriteLine($"Primes: {count}"); int CountPrimes(int max) => Enumerable.Range(2, max - 1).Count(IsPrime); bool IsPrime(int n){ for (int d = 2; d * d <= n; d++) if (n % d == 0) return false; return true;}$ dotnet run CpuBound.csPrimes: 14893333.6 Checkpoint: print order
- An async method runs synchronously until its first await, so C prints right after A.
- At the await it returns an incomplete Task, so B prints next; after the delay come D, then E.
- Answer: A C B D E.
Console.WriteLine("A");Task task = SaveOrderAsync();Console.WriteLine("B");await task;Console.WriteLine("E"); async Task SaveOrderAsync(){ Console.WriteLine("C"); await Task.Delay(100); Console.WriteLine("D");}$ dotnet run Order.csACBDE33.7 The .Result / .Wait deadlock
- WinForms, WPF and old ASP.NET have a SynchronizationContext that sends the continuation back to the same UI thread.
- Console apps and ASP.NET Core have no such context ("Console context null? True"), so this deadlock does not happen there.
- The demo builds SingleThreadContext whose Post queues the continuation, like a UI thread.
- task.Wait (same as .Result, with a timeout for the demo) blocks the only thread that could run the queued continuation.
// WinForms/WPF jaisa: continuation ek hi// thread ki queue me jaata haiclass SingleThreadContext : SynchronizationContext{ public readonly ConcurrentQueue<Action> Queue = new(); public override void Post( SendOrPostCallback d, object? state) => Queue.Enqueue(() => d(state));}var ui = new SingleThreadContext();SynchronizationContext .SetSynchronizationContext(ui); Task<decimal> task = GetPriceAsync();bool done = task.Wait(TimeSpan.FromSeconds(3));Console.WriteLine(done ? $"Price: {task.Result}" : "Deadlock: 3 sec baad bhi wait");Console.WriteLine($"Pending: {ui.Queue.Count}"); async Task<decimal> GetPriceAsync(){ await Task.Delay(500); return 1899m;}$ dotnet run Deadlock.csConsole context null? TrueDeadlock: 3 sec baad bhi waitPending: 1- Step 1
1.UI thread calls GetPriceAsync().Result and blocks
- Step 2
2.Task.Delay(500) completes
- Step 3
3.Continuation is posted to the UI context queue
- Step 4
4.Only the UI thread runs that queue, and it is blocked
- Step 5
5.Each waits for the other forever: Pending 1
Fix: await all the way; ConfigureAwait(false) in libraries
- Best fix: async all the way, the caller also awaits instead of .Result/.Wait.
- In library code add ConfigureAwait(false) so the continuation is not sent back to the context.
// UI thread: async all the wayvar price = await GetPriceAsync(); // Library codeasync Task<decimal> GetPriceAsync(){ await Task.Delay(500) .ConfigureAwait(false); return 1899m;}33.8 async void vs async Task
- async void gives the caller no Task, so an exception never reaches the caller's catch and crashes the process.
- async Task can be awaited and the exception lands in the catch: "Caught: SMS failed".
- async void is only for UI event handlers, whose signature must be void.
try{ SendSms("98XXXXXX10"); await Task.Delay(500);}catch (Exception ex){ Console.WriteLine($"Caught: {ex.Message}");} async void SendSms(string phone){ await Task.Delay(100); throw new Exception("SMS failed");}try{ await SendSmsAsync("98XXXXXX10");}catch (Exception ex){ Console.WriteLine($"Caught: {ex.Message}");} async Task SendSmsAsync(string phone){ await Task.Delay(100); throw new Exception("SMS failed");}33.9 ValueTask: zero allocation on a cache hit
- Every Task-returning async method allocates a Task, even when the result is ready immediately.
- ValueTask<T> returns a synchronous result (cache hit) without allocation; async work only on a miss.
- Release run: 1000 calls cost 80000 bytes with Task and 0 bytes with ValueTask.
- Keep Task as the default; use ValueTask only on a measured hot path (and await it only once).
async ValueTask<decimal> GetPriceAsync(int id){ if (cache.TryGetValue(id, out var price)) return price; // cache hit: no allocation await Task.Delay(200); // cache miss: DB call return 999m;}$ dotnet run -c Release ValueTaskDemo.cs1000 calls, Task: 80000 bytes1000 calls, ValueTask: 0 bytes33.10 Common mistakes
- Blocking with .Result or .Wait(): deadlock risk in apps with a context, thread starvation everywhere.
- Thread.Sleep in async code instead of await Task.Delay.
- async void for anything other than event handlers.
- Wrapping I/O calls in Task.Run in ASP.NET Core: it only moves the wait to another pool thread.
- Myth: async makes code faster or runs it on a new thread. A single call is not faster and await creates no thread; the benefit is scalability.
33.11 Rules
- Async all the way; never block with .Result / .Wait.
- async void only for event handlers.
- I/O bound: just await the async API.
- Task.Run only for CPU bound work.
- Libraries: ConfigureAwait(false); ValueTask only on a measured hot path.
33.12 Interview tips
- await pauses the method on an incomplete Task and frees the thread; the rest runs later as a continuation.
- I/O bound work gains scalability with async; CPU bound work uses Task.Run.
- .Result/.Wait can deadlock where a SynchronizationContext exists (UI, old ASP.NET), so stay async all the way.
- async void exceptions cannot be caught by the caller; use async Task.
- ValueTask avoids allocation when results are often synchronous; Task stays the default.