Skip to content
Tutorials Center
My learning

Topics

Lesson 105 of 182 ยท Async and Concurrency

Async Patterns and Pitfalls

Avoid the classic async and await mistakes in C# - forgotten await, fire-and-forget, async void, sync-over-async deadlocks, context capture, lost exceptions, async disposal, testing, and a checklist.

async and await make asynchronous code read like normal code, and that is also their trap: code that looks sequential but is not, errors that vanish, programs that freeze for no visible reason. Almost every async bug falls into a handful of families. Once you can name them, you can spot them in code review in seconds.

This lesson is a tour of those families with a runnable example for each: forgotten await, fire-and-forget, async void, blocking on tasks (sync-over-async) and the deadlock it can cause, context capture and ConfigureAwait, exceptions that get lost, returning a task from inside using, async disposal, and how to test async code without waiting on real clocks. It assumes you know async and await, tasks and cancellation.

Pitfall 1: forgetting to await

An async method returns a Task immediately, as soon as it hits its first real await. If you do not await that task, your code carries on while the work is still running, and any exception it throws is never seen.

C# A missing await (warns on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The compiler warns about it: warning CS4014: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call. Treat CS4014 as an error in real projects. The fix is simply await SaveAsync(); (or storing the task and awaiting it later, as in await Task.WhenAll(...)).

Pitfall 2: fire-and-forget

Sometimes you really do not want to wait: sending a metrics ping, warming a cache. Doing it safely means answering two questions: who sees the exception? and what if the process shuts down meanwhile? A bare, unawaited call answers neither.

A small helper can at least make sure failures are observed:

C# A safer fire-and-forget

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The wrapper catches and logs, so the failure cannot be lost, and keeping the tasks in a list lets shutdown wait for them. In a real service, hand background work to a queue and a hosted worker instead (see Channels and the background job queue project); that gives you retries, limits and clean shutdown.

Pitfall 3: async void

An async void method has no task for the caller to await or catch from. Two consequences:

  1. The caller cannot know when it finishes.
  2. An exception thrown in it is raised directly on the thread pool (or the captured synchronization context) and, unless something handles it globally, crashes the process. A try/catch around the call cannot catch it.

Use async void for exactly one thing: event handlers, whose signatures are fixed. Everywhere else return Task.

C# async void crashes the process (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The program ends with Unhandled exception. System.InvalidOperationException: boom from async void. Had ExplodeAsync returned Task, the exception would have been stored in the task and surfaced at an await.

The same trap hides in lambdas. list.ForEach(async x => await ProcessAsync(x)) compiles because the lambda is converted to Action, which makes it an async void lambda: nothing waits for it and failures crash. Use a foreach with await, Task.WhenAll(list.Select(ProcessAsync)), or Parallel.ForEachAsync (see Parallel and PLINQ).

Pitfall 4: blocking on async code (sync-over-async)

task.Result, task.Wait() and task.GetAwaiter().GetResult() block the current thread until the task completes. Blocking wastes a thread, hurts scalability in servers, and, in some environments, deadlocks.

The deadlock needs a synchronization context: an object that says "continuations must run on this particular thread" (the UI thread of a desktop app, or the old ASP.NET request context). By default await captures the current context and resumes on it. Now combine:

  1. The UI thread calls GetValueAsync().Wait() and blocks, waiting for the task.
  2. The task finishes its delay and wants to resume the rest of GetValueAsync on the UI thread.
  3. The UI thread is blocked waiting for the task. Neither can move: deadlock.

Console apps and ASP.NET Core have no such context, so you will not see this there, which is why the bug often appears only when code moves to a UI app or a library is reused. We can reproduce it by building a tiny single-thread context. The wait has a timeout so the example reports the deadlock instead of hanging.

C# Reproducing the sync-over-async deadlock

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

In the first call, Wait(300) blocks the only context thread, the delay finishes, but the continuation is stuck in the queue behind the blocked callback, so after 300 ms Wait gives up and returns false. In the second call the continuation does not need the context, so the task completes and Wait returns true.

The real fix is never block: make the whole call chain async and await all the way up ("async all the way"). ConfigureAwait(false) is a mitigation, not a license to block.

If you absolutely must call async code from synchronous code (for example in a Main of an old project, or a framework callback you do not control), do it at the very edge, once, with GetAwaiter().GetResult(), which throws the original exception instead of an AggregateException. Never do it in the middle of async code.

Context capture and ConfigureAwait

When an await completes, the rest of the method (the continuation) runs on the captured synchronization context if there is one, otherwise on the thread pool. In a UI app that is what you want: after await LoadAsync() you can update controls. In library code that never touches the UI it only adds cost and deadlock risk, so the convention is await x.ConfigureAwait(false) throughout libraries.

Rules of thumb:

  • Application code (UI handlers, ASP.NET Core controllers and endpoints): no ConfigureAwait needed. ASP.NET Core has no synchronization context, so it changes nothing there.
  • General-purpose libraries: use ConfigureAwait(false) on every await, because you do not know who will call you.
  • ConfigureAwait(false) applies to that one await. It does not change the context for code after later awaits you forgot to mark.
  • Never access UI objects after ConfigureAwait(false); you may be on a pool thread.

Pitfall 5: exceptions that disappear

When an async Task method throws, the exception is stored inside the returned task. It is rethrown when someone awaits the task. If nobody ever awaits it (fire-and-forget), nobody ever sees it.

A second subtlety: Task.WhenAll collects all exceptions from its tasks, but await rethrows only the first one. To see them all, inspect the task you awaited.

C# Await shows one exception, the task holds all

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Also remember that exceptions of a task that is never awaited can surface much later, when the garbage collector finalizes the task, as TaskScheduler.UnobservedTaskException. In modern .NET this no longer crashes the process by default, so such failures are simply silent: a worse outcome.

Pitfall 6: returning a task from inside using

Eliding async/await (returning the inner task directly) is a small optimization, and it is wrong whenever the method holds something that must live until the task completes: a using block, a try/finally, or a lock. The method returns the task immediately, the using block ends, the resource is disposed, and the operation is still running against a disposed object.

C# Disposed before the work finishes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

In the wrong version, "resource disposed" prints before the work has finished. Rule: if the method has a using, try, catch, finally or lock around the task, keep async and await. Only elide in plain pass-through methods (public Task SaveAsync() => _repo.SaveAsync();).

Async disposal

Some resources need to do asynchronous work to clean up: flush a buffer to disk, send a goodbye message, return a connection. For these there is IAsyncDisposable with a DisposeAsync() method returning ValueTask, used with await using. Do not block inside Dispose() on async cleanup; implement IAsyncDisposable instead (and IDisposable as well if sync callers exist).

C# await using and IAsyncDisposable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The same pattern is what await foreach uses for the enumerator of an async stream. More on disposal basics is in IDisposable and using.

Testing async code

Async tests are ordinary tests that return Task and use await: test runners such as xUnit and NUnit wait for the task. Never write async void tests or use .Result. The hard part is time: code with Task.Delay, timeouts and retries makes tests slow and flaky if it uses the real clock.

The cure is to inject the source of delay. The example tests a retry helper with a fake delay that records the requested wait times instead of waiting. Because our sandbox has no test framework, the "tests" are a tiny hand-written runner (in a real project this would be [Fact] methods; the packages are shown below).

C# Testing retries with a fake delay

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

In a real xUnit project the same checks look like this (read-only, needs the xUnit NuGet package and the dotnet test command):

C#
// Read-only: requires the xunit NuGet package
public class RetryTests
{
    [Fact]
    public async Task Retries_until_success()
    {
        int attempts = 0;
        var result = await Retry.RunAsync(async () =>
        {
            attempts++;
            await Task.Yield();
            return attempts < 3 ? throw new InvalidOperationException() : "ok";
        }, maxAttempts: 5, delay: _ => Task.CompletedTask);

        Assert.Equal("ok", result);
        Assert.Equal(3, attempts);
    }
}

.NET also has TimeProvider (an abstraction over the clock and timers, with Task.Delay(TimeSpan, TimeProvider) overloads) and a FakeTimeProvider in the Microsoft.Extensions.TimeProvider.Testing package that lets a test advance time instantly. Accept a TimeProvider in your constructor and tests need no real waiting. See the testing lessons later in this course.

Other habits worth having

  • Don't wrap async work in Task.Run just to look async. Task.Run(() => SomethingAsync()) in a server adds a pointless thread hop. Use Task.Run to move CPU-bound work off a UI thread.
  • Don't fake async. A method that is truly synchronous should be synchronous. Task.FromResult is the way to return a ready value from an async-shaped API.
  • Use ValueTask<T> sparingly. It saves an allocation when a method usually completes synchronously, but it must be awaited exactly once, and never awaited twice or blocked on.
  • Put timeouts on external calls: await task.WaitAsync(TimeSpan.FromSeconds(5)) or a CancellationTokenSource with a timeout (see Cancellation and Timeouts).
  • Don't hold a lock across an await. Use SemaphoreSlim (lock, Lock and Interlocked).
  • Avoid shared mutable state in concurrent async code, or protect it; use concurrent collections.

The checklist

Do Don't
Return Task/Task<T>/ValueTask<T> and name methods ...Async Write async void (except event handlers)
await every task you start, or store it and await it later Ignore CS4014 warnings
Be async all the way up the call chain Call .Result, .Wait(), .GetAwaiter().GetResult() in the middle of async code
Accept and pass on a CancellationToken Start long operations that can never be stopped
Use ConfigureAwait(false) in general-purpose libraries Touch UI objects after ConfigureAwait(false)
Keep async/await when there is a using/try/lock Return an inner task from inside a using
await using for async cleanup Block inside Dispose() on async work
Inject delays and clocks so tests are fast Use Thread.Sleep or real delays in tests

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens to an exception thrown inside an async void method?

    async void has no task to hold the exception, so it is raised directly and, unhandled, terminates the process. Return Task instead.
  2. 2. Why can .Wait() on an async method deadlock in a UI app?

    await captures the synchronization context. The blocked context thread can never run the continuation that would complete the task.
  3. 3. await Task.WhenAll(a, b, c) where all three fail. How many exceptions does the await throw?

    await unwraps the AggregateException and rethrows only the first inner exception. Keep the task and read task.Exception.InnerExceptions for all of them.
  4. 4. Why is using var r = new R(); return r.WorkAsync(); in a non-async method a bug?

    Without await the using block ends at once and disposes the resource before the task has finished. Make the method async and await.
  5. 5. How do you keep tests of retry or timeout logic fast and reliable?

    Injecting the source of time lets tests advance instantly and deterministically.

Summary

  • Always await the tasks you start; the compiler warning CS4014 flags forgotten ones. Fire-and-forget needs a wrapper that logs failures and a plan for shutdown.
  • Use async void only for event handlers; elsewhere return Task. Async lambdas passed as Action silently become async void.
  • Do not block on tasks: .Result/.Wait() waste threads and can deadlock when a synchronization context is captured. Be async all the way; ConfigureAwait(false) belongs in general-purpose libraries.
  • await rethrows only the first exception of Task.WhenAll; the task holds all of them. Unobserved task exceptions are silent.
  • Keep async/await when a using, try or lock surrounds the call; use IAsyncDisposable and await using for async cleanup.
  • Test async code with Task-returning tests and injected delays or TimeProvider, never real sleeps.

Next: Garbage Collection