wasAsked.

Explain async and await in C#, including thread-pool starvation, cancellation, and common deadlock causes.

Freshworks · Full Stack Developer · 3-4-years · technical

Published

Year not specified · .NET, C#, Software Engineering

Community answers

Posted by wasAsked editorial collection

An async method runs synchronously until it reaches an incomplete await. It then returns a Task and registers the remainder as a continuation. `await` does not itself create a thread. For true asynchronous I/O, no application thread needs to remain blocked while the operation is pending. ```csharp public async Task<Customer?> LoadAsync(int id, CancellationToken ct) { using var response = await http.GetAsync($"customers/{id}", ct); if (response.StatusCode == HttpStatusCode.NotFound) return null; response.EnsureSuccessStatusCode(); return await response.Content.ReadFromJsonAsync<Customer>(cancellationToken: ct); } ``` Thread-pool starvation occurs when work is queued but available worker threads are blocked, often by `.Result`, `.Wait()`, synchronous I/O, or long locks. Prefer async all the way and pass cancellation tokens. Classic UI or legacy ASP.NET deadlocks can occur when synchronous code blocks a context thread while the awaited continuation needs that same context. ASP.NET Core does not install that synchronization context, but blocking still harms scalability. Use `async void` only for event handlers; otherwise return `Task` so callers can await completion and observe exceptions.

Krishna Yadav · · 0 likes

async and await let a method wait for I/O without blocking a thread. When an await hits an incomplete Task, the method returns to its caller and the thread goes back to the pool; when the operation completes, the rest of the method continues as a continuation. public async Task<Order?> GetOrderAsync(int id, CancellationToken ct) { var order = await _db.Orders.FindAsync([id], ct); // thread released while SQL runs return order; } Async is mainly for I/O-bound work (database, HTTP, files). For CPU-bound work it adds no benefit by itself; use Task.Run only in UI apps or deliberately offloaded workloads, not in ASP.NET Core request handlers. Thread-pool starvation - Happens when pool threads are blocked waiting synchronously — calling .Result, .Wait() or GetAwaiter().GetResult() on tasks, or doing synchronous I/O. - New work waits for threads, the pool grows slowly, and latency climbs sharply under load. - Fix: async all the way down; use async APIs (ToListAsync, ReadAsync); avoid sync-over-async. dotnet-counters shows rising thread count and queue length. Cancellation - Accept a CancellationToken and pass it to every async call. In ASP.NET Core, HttpContext.RequestAborted (or a CancellationToken action parameter) is cancelled when the client disconnects. - Use CancellationTokenSource.CancelAfter for timeouts, and link tokens with CreateLinkedTokenSource. - Expect OperationCanceledException and do not log it as an error when it is a client disconnect. Common deadlock causes - Sync-over-async in environments with a SynchronizationContext (WinForms, WPF, classic ASP.NET): the blocked thread is the one the continuation needs. ConfigureAwait(false) in library code avoids capturing the context. ASP.NET Core has no SynchronizationContext, so it shows starvation instead of a classic deadlock. - Locks held across awaits: you cannot await inside lock; use SemaphoreSlim.WaitAsync. - async void methods: exceptions cannot be caught by the caller; use them only for event handlers. Other tips: ValueTask for hot paths that often complete synchronously, Task.WhenAll for independent operations, and never fire-and-forget without handling exceptions.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics