Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    Cheat sheets: all cheat sheets

    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

    • await does 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 void is for event handlers only. Other async methods return Task or ValueTask (with or without a result); async iterators return IAsyncEnumerable<T>.
    • Do not block with .Result or .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 CancellationToken to everything that accepts one.

    Pitfalls and fixes

    PitfallWhat goes wrongFix
    async void methodthe caller cannot await it; an exception goes to the captured SynchronizationContext, or the thread pool if there is none, and can end the processreturn 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 reacha 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 Coreasync all the way up: Main, controllers and handlers
    _ = DoAsync(); inside a requestfailures go unobserved; the work can outlive the request and use a disposed DbContextawait it, or queue it to a BackgroundService with its own scope
    return SomethingAsync(stream); inside using or tryif the task is still running, the scope ends first, and a catch misses its failurekeep async and await when cleanup or a catch must cover the work
    starting each independent call only after awaiting the previous onelatency adds up: A + B + Cstart them all first, then await Task.WhenAll(a, b, c)
    enumerating items.Select(async ...) over 10,000 items, for example in Task.WhenAll10,000 calls start at once: sockets, connection pools or rate limits run outParallel.ForEachAsync with MaxDegreeOfParallelism, or a SemaphoreSlim
    await inside lockcompile error CS1996SemaphoreSlim.WaitAsync() and Release() in try/finally
    a ValueTask awaited twice, or .Result read earlyundefined behavior: pooled sources are reusedconsume it once; call .AsTask() once if you need a Task
    no CancellationTokenwork continues after the client left or the host stopsaccept a token and pass it on; HttpContext.RequestAborted for request work
    Task.Run around async I/O in ASP.NET Coreextra scheduling, no gainawait the I/O directly; Task.Run is for CPU work off a UI thread
    TaskCompletionSource without optionsSetResult can run continuations inline: reentrancy or deadlocksTaskCreationOptions.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

    C#Runs
    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();
    }
    Output
    elided: ObjectDisposedException
    awaited: hello
    • ReadElided returns the pending task, and its using disposes the reader at once. When the read resumes, the reader is gone.
    • ReadAwaitedAsync awaits inside the scope, so the reader lives until the read is done.
    • Returning the task directly is fine when no using, try or catch in the method must cover the work.

    Exceptions you never see, and cancellation

    C#Runs
    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);
    }
    Output
    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 a TaskScheduler.UnobservedTaskException event after garbage collection, which does not end the process on modern .NET.
    • await both threw one of the two exceptions; both.Exception.InnerExceptions has both. Do not rely on which one await picks.
    • Task.Delay reports cancellation as TaskCanceledException, which derives from OperationCanceledException: 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) with CancelAfter(...): a cancellation budget for one call; cooperative, not a guaranteed return time.
    • await using for IAsyncDisposable; await foreach with WithCancellation(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 an async void callback.
    • ConfigureAwaitOptions (.NET 8): SuppressThrowing works on a non-generic Task only; Task<T>.ConfigureAwait refuses it.

    Common mistakes in code review

    C#
    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 token

    These 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?

    A It does not compile
    B The lambda becomes async void
    C It runs the items in parallel threads
    D It awaits each item in order
    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?

    A None: using waits for the read
    B The reader is disposed before the read completes
    C The compiler adds the await
    D The read runs twice
    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?

    A An AggregateException with both
    B One of the two exceptions
    C Nothing
    D Always the first task's exception
    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.

    Sources

    TechInterviewNotes Editorial Team · Updated 28 Nov 2026 ·