C# async/await Pitfalls Cheat Sheet
Spot blocking, lost exceptions and async void mistakes.
The async/await mistakes that C# code reviews and interviews keep finding (blocking on tasks, lost exceptions, async void, early disposal, unbounded fan-out, missing cancellation), each with its fix.
At a glance
awaitdoes not start a thread. A completed task normally continues without suspending; an incomplete one registers the rest of the method as a continuation.- Almost every pitfall is one of three things: blocking on a task, losing a task (and its exception), or ending a resource's scope before the task finishes.
async voidis for event handlers only. Other async methods returnTaskorValueTask(with or without a result); async iterators returnIAsyncEnumerable<T>.- Do not block with
.Resultor.Wait(): it can deadlock in a UI or old ASP.NET context, and it starves the thread pool in ASP.NET Core under load. await Task.WhenAll(...)throws one exception; the combined task holds all of them.- Bound fan-out, and pass a
CancellationTokento everything that accepts one.
Pitfalls and fixes
| Pitfall | What goes wrong | Fix |
|---|---|---|
async void method | the caller cannot await it; an exception goes to the captured SynchronizationContext, or the thread pool if there is none, and can end the process | return Task; async void only for event handlers |
async lambda passed as an Action (list.ForEach(async x => ...)) | it becomes async void: fire-and-forget, exceptions out of reach | a plain foreach with await, or Parallel.ForEachAsync |
.Result, .Wait(), GetAwaiter().GetResult() | deadlock when the continuation needs the blocked context; thread-pool starvation in ASP.NET Core | async all the way up: Main, controllers and handlers |
_ = DoAsync(); inside a request | failures go unobserved; the work can outlive the request and use a disposed DbContext | await it, or queue it to a BackgroundService with its own scope |
return SomethingAsync(stream); inside using or try | if the task is still running, the scope ends first, and a catch misses its failure | keep async and await when cleanup or a catch must cover the work |
| starting each independent call only after awaiting the previous one | latency adds up: A + B + C | start them all first, then await Task.WhenAll(a, b, c) |
enumerating items.Select(async ...) over 10,000 items, for example in Task.WhenAll | 10,000 calls start at once: sockets, connection pools or rate limits run out | Parallel.ForEachAsync with MaxDegreeOfParallelism, or a SemaphoreSlim |
await inside lock | compile error CS1996 | SemaphoreSlim.WaitAsync() and Release() in try/finally |
a ValueTask awaited twice, or .Result read early | undefined behavior: pooled sources are reused | consume it once; call .AsTask() once if you need a Task |
no CancellationToken | work continues after the client left or the host stops | accept a token and pass it on; HttpContext.RequestAborted for request work |
Task.Run around async I/O in ASP.NET Core | extra scheduling, no gain | await the I/O directly; Task.Run is for CPU work off a UI thread |
TaskCompletionSource without options | SetResult can run continuations inline: reentrancy or deadlocks | TaskCreationOptions.RunContinuationsAsynchronously |
ConfigureAwait(false) in a general-purpose library avoids capturing a context. It does not make blocking safe, and ASP.NET Core installs no SynchronizationContext by default.
Early disposal when the await is left out
var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
Task<string> elided = ReadElided(gate.Task);
gate.SetResult();
try { Console.WriteLine(await elided); }
catch (ObjectDisposedException) { Console.WriteLine("elided: ObjectDisposedException"); }
Console.WriteLine($"awaited: {await ReadAwaitedAsync()}");
static Task<string> ReadElided(Task gate)
{
using var reader = new StringReader("hello");
return SlowReadAsync(reader, gate); // the reader is disposed when this returns
}
static async Task<string> ReadAwaitedAsync()
{
using var reader = new StringReader("hello");
return await SlowReadAsync(reader, Task.Delay(10)); // disposed after the read
}
static async Task<string> SlowReadAsync(TextReader reader, Task gate)
{
await gate;
return reader.ReadToEnd();
}elided: ObjectDisposedException awaited: hello
ReadElidedreturns the pending task, and itsusingdisposes the reader at once. When the read resumes, the reader is gone.ReadAwaitedAsyncawaits inside the scope, so the reader lives until the read is done.- Returning the task directly is fine when no
using,tryorcatchin the method must cover the work.
Exceptions you never see, and cancellation
Task forgotten = FailAsync("C"); // started and never awaited
await Task.WhenAny(forgotten); // waits without observing the fault
Console.WriteLine($"faulted, nothing printed: {forgotten.IsFaulted}");
try { await forgotten; }
catch (InvalidOperationException ex) { Console.WriteLine($"seen when observed: {ex.Message}"); }
Task both = Task.WhenAll(FailAsync("A"), FailAsync("B"));
try { await both; }
catch (InvalidOperationException)
{
Console.WriteLine($"await threw one; the task holds {both.Exception!.InnerExceptions.Count}");
}
using var cts = new CancellationTokenSource();
cts.Cancel();
try { await Task.Delay(TimeSpan.FromSeconds(5), cts.Token); }
catch (OperationCanceledException ex) { Console.WriteLine($"cancelled: {ex.GetType().Name}"); }
static async Task FailAsync(string name)
{
await Task.Yield();
throw new InvalidOperationException(name);
}faulted, nothing printed: True seen when observed: C await threw one; the task holds 2 cancelled: TaskCanceledException
- A faulted task keeps its exception, and code learns of it only by observing it:
await,.Wait(), or reading.Exception. If nobody does, the failure goes unnoticed: at most aTaskScheduler.UnobservedTaskExceptionevent after garbage collection, which does not end the process on modern .NET. await boththrew one of the two exceptions;both.Exception.InnerExceptionshas both. Do not rely on which oneawaitpicks.Task.Delayreports cancellation asTaskCanceledException, which derives fromOperationCanceledException: catch the base type.
Useful APIs since .NET 6
task.WaitAsync(timeout, token): a time limit on the wait. The operation itself is not cancelled.Parallel.ForEachAsync(items, new ParallelOptions { MaxDegreeOfParallelism = 8, CancellationToken = ct }, async (item, ct) => ...): bounded async loops.CancellationTokenSource.CreateLinkedTokenSource(ct)withCancelAfter(...): a cancellation budget for one call; cooperative, not a guaranteed return time.await usingforIAsyncDisposable;await foreachwithWithCancellation(ct), and[EnumeratorCancellation]on the iterator's token parameter.Task.WhenEach(.NET 9): process tasks in the order they complete.PeriodicTimer: a timer loop you await, instead of a timer with anasync voidcallback.ConfigureAwaitOptions(.NET 8):SuppressThrowingworks on a non-genericTaskonly;Task<T>.ConfigureAwaitrefuses it.
Common mistakes in code review
public async void Save() => await repo.SaveAsync(); // async void: return Task
var user = userService.GetAsync(id).Result; // blocking: thread-pool starvation
public Task<string> ReadAsync()
{
using var reader = File.OpenText(path);
return reader.ReadToEndAsync(); // disposed while the read may still run
}
items.ForEach(async i => await SendAsync(i)); // Action<T>: becomes async void
await Task.WhenAll(urls.Select(u => http.GetStringAsync(u))); // 10,000 requests at once, no tokenThese lines are fragments to recognize in a review; repo, userService, path, SendAsync, urls and http belong to the application.
In an interview
What does await do, and does it start a thread? If the awaited task is complete, the method normally just continues. If not, the rest of the method becomes a continuation and the method returns. await never starts a thread itself.
When can .Result deadlock, and is blocking safe in ASP.NET Core? It deadlocks when the task's continuation needs the context the caller is blocking, as in a UI app or old ASP.NET. ASP.NET Core has no such context, but blocking still ties up pool threads and causes starvation under load.
When can you drop async and await and return the task directly? When no using, try, catch or other code in the method must run after the task completes, and moving exceptions from the call to the await is acceptable.
How do you see every exception from Task.WhenAll? Keep the combined task. After the await throws, read task.Exception.InnerExceptions, or check each input task. A cancelled-only result has no exceptions to read.
Why can't you await inside lock, and what do you use? A lock is held by a thread, and code after an await may run on another one; the compiler refuses it (CS1996). Use SemaphoreSlim.WaitAsync and release it in finally.
What are the rules for ValueTask? Consume it once: await it, or call .AsTask() once and use that task. Never await it twice or read .Result before it completes.
Does WaitAsync(timeout) cancel the work? No. It only stops waiting; the operation keeps running and still needs an owner, or a token that really cancels it.
Check yourself
Why is list.ForEach(async x => await SendAsync(x)) a problem?
Show answer
Correct answer: B
List<T>.ForEach takes an Action<T>, so the async lambda becomes async void: nothing awaits it, and its exceptions are lost to the caller.
Option A: An async lambda converts to Action<T>, so it compiles.
Option C: ForEach calls the lambda on the same thread; it simply does not wait for each call.
Option D: ForEach cannot await an async void lambda.
A method has using var reader = ...; and ends with return reader.ReadToEndAsync(); without await. The read is still running when the method returns. What is the risk?
Show answer
Correct answer: B
The method returns the pending task, and its using disposes the reader immediately; keep async and await inside the scope.
Option A: using disposes at the end of the method's scope; it does not wait for a task it did not await.
Option C: The compiler adds no await; the method is not even async.
Option D: Nothing repeats the read.
Two tasks in Task.WhenAll fail. What does await on the combined task throw?
Show answer
Correct answer: B
await rethrows one exception; the combined task's Exception.InnerExceptions holds both.
Option A: await does not wrap them; .Wait() would throw an AggregateException.
Option C: The combined task is faulted, so awaiting it throws.
Option D: Which one is chosen is not guaranteed.
Related on TechInterviewNotes
Sources
- Asynchronous programming with async and await: how
awaitsuspends and resumes. - Async return types:
Task,ValueTask,async voidand its exceptions. - ASP.NET Core best practices: avoid blocking calls and thread-pool starvation.
- ValueTask<TResult>: consume it once.
- Task.WhenAll: the combined task and its exceptions.
- ConfigureAwait FAQ: what
ConfigureAwait(false)does and does not do.
TechInterviewNotes Editorial Team · Updated 28 Nov 2026 ·