2.1 How Async/Await Works Internally
// What you write:
public async Task<string> GetDataAsync()
{
var result = await httpClient.GetStringAsync(url);
return result.ToUpper();
}
// What the compiler generates (simplified):
// 1. A state machine struct implementing IAsyncStateMachine
// 2. States: 0 = initial, 1 = awaiting HTTP, -1 = complete
// 3. MoveNext() advances through states, resuming after each await
Async/await does not create new threads. await releases the current thread back to the thread pool while waiting on I/O; the continuation resumes on whatever thread pool thread is available (unless a SynchronizationContext — like ASP.NET classic or WPF’s UI thread — captures a specific context to resume on).
2.2 Common Pitfalls
// WRONG: Blocking on async (deadlock risk when a SynchronizationContext is present)
public string GetData()
{
return GetDataAsync().Result; // Can deadlock in ASP.NET classic / WPF / WinForms
}
// RIGHT: async all the way
public async Task<string> GetData() => await GetDataAsync();
// WRONG: async void — fire-and-forget, exceptions are lost / crash the process
public async void ProcessOrder(Order order)
{
await _service.ProcessAsync(order);
}
// RIGHT: async Task
public async Task ProcessOrder(Order order) => await _service.ProcessAsync(order);
// WRONG: sequential awaits when tasks are independent
foreach (var item in items)
await ProcessItemAsync(item); // Sequential — slow!
// RIGHT: parallel execution
var tasks = items.Select(item => ProcessItemAsync(item));
await Task.WhenAll(tasks);
// WRONG: not using ConfigureAwait(false) in library code
await httpClient.GetAsync(url); // Captures SynchronizationContext unnecessarily
// RIGHT: in library/non-UI code, avoid capturing context
await httpClient.GetAsync(url).ConfigureAwait(false);
Why .Result/.Wait() deadlocks: in a context with a SynchronizationContext (classic ASP.NET, WPF, WinForms — NOT ASP.NET Core, which has none by default), the continuation after await tries to resume on the captured context (e.g., the single UI thread). If that same thread is blocked synchronously waiting on .Result, the continuation can never run, and the thread waits on itself forever. ConfigureAwait(false) tells the awaiter not to bother resuming on the original context, breaking this cycle in library code.
2.3 Thread Pool Starvation
Thread pool starvation happens when many requests block synchronously on I/O (.Result, .Wait(), synchronous DB/HTTP calls) inside async handlers. Each blocked thread occupies a thread-pool slot; the pool grows slowly (about one new thread every ~1-2 seconds under sustained pressure) so under a burst of load, all requests queue behind the growth throttle, and latency spikes even though CPU utilization looks low.
// Diagnose with dotnet-counters
dotnet-counters monitor --process-id <PID> System.Runtime
// Watch: threadpool-thread-count, threadpool-queue-length
// Fix: async all the way, no .Result/.Wait() in request-handling code paths
// Fix: increase minimum thread pool size only as a stopgap, not a real fix
ThreadPool.SetMinThreads(workerThreads: 200, completionPortThreads: 200);
2.4 Channels & SemaphoreSlim
var channel = Channel.CreateBounded<WorkItem>(new BoundedChannelOptions(100)
{
FullMode = BoundedChannelFullMode.Wait,
SingleReader = false,
SingleWriter = false
});
async Task ProduceAsync(ChannelWriter<WorkItem> writer)
{
foreach (var item in GetWorkItems())
await writer.WriteAsync(item);
writer.Complete();
}
async Task ConsumeAsync(ChannelReader<WorkItem> reader)
{
await foreach (var item in reader.ReadAllAsync())
await ProcessAsync(item);
}
// SemaphoreSlim for throttling concurrent async operations
private readonly SemaphoreSlim _throttle = new(maxConcurrency: 10);
public async Task ProcessBatchAsync(IEnumerable<Item> items)
{
var tasks = items.Select(async item =>
{
await _throttle.WaitAsync();
try { await ProcessItemAsync(item); }
finally { _throttle.Release(); }
});
await Task.WhenAll(tasks);
}
Interview Q&A — Section 2
Q1: Your API handles 10K requests/sec but latency spikes occur every few seconds. What would you investigate?
A: First, GC pauses — check if Gen 2 collections correlate with the spikes; mitigate with reduced allocations, object pooling,
Span<T>. Second, thread pool starvation — look for blocking calls (.Result,.Wait()) inside async code paths; fix by going async all the way. Third, lock contention fromlockstatements creating bottlenecks; considerConcurrentDictionaryor lock-free patterns. Fourth, connection pool exhaustion — HttpClient or DB connections not returned; useIHttpClientFactoryand check pool sizing. Fifth, synchronous logging blocking the request thread; switch to async, structured logging (Serilog).
Q2: How does async/await work under the hood, and why doesn’t it create new threads?
A: The compiler transforms an async method into a state machine; each
awaitis a state transition. If the awaited task is already complete, execution continues synchronously on the same thread — no thread switch at all. If it’s incomplete, the state machine registers a continuation and returns control to the caller, releasing the current thread back to the pool. When the awaited operation completes, the continuation runs on whichever thread pool thread is available next (unless a capturedSynchronizationContextforces it back onto a specific thread).
Q3: Why does .Result deadlock in ASP.NET classic/WPF but usually not in ASP.NET Core?
A: ASP.NET Core has no
SynchronizationContextby default, so continuations resume on any available thread-pool thread — blocking on.Resulton one thread doesn’t prevent the continuation from running elsewhere. In contexts that do have aSynchronizationContext(classic ASP.NET’s request context, WPF/WinForms’ UI thread), the continuation specifically wants to resume on that captured context; if that same thread is already blocked synchronously waiting for the result, you get a genuine deadlock.ConfigureAwait(false)avoids this by not capturing the context at all — a best practice in library and non-UI code regardless of host.
Q4: What’s the difference between Task and ValueTask, and when would you use each?
A:
Task<T>always allocates on the heap.ValueTask<T>is a struct that avoids that allocation when the result is already available synchronously (cache hit, buffered read) — valuable in extremely hot paths called millions of times. UseTaskby default; it’s simpler and safer sinceValueTaskhas real restrictions (can only be awaited once, shouldn’t be stored or awaited twice). Reach forValueTaskonly after profiling shows the allocation actually matters.