Skip to content
Tutorials Center
My learning

Topics

Lesson 97 of 182 ยท Async and Concurrency

async and await

Understand C# async and await - how the state machine works, writing async methods, the async void trap, ConfigureAwait, async Main, sync-over-async deadlocks and ValueTask.

Programs spend most of their time waiting: for a network reply, a disk read, a timer. If the thread that asked sits there doing nothing, that thread is wasted. On a server handling thousands of requests, wasted threads mean wasted memory and lower throughput; in a desktop app, a blocked UI thread means a frozen window. Asynchronous programming lets a method say "I will continue when the result is ready, and meanwhile this thread can do something else".

C# makes this almost as easy as ordinary code with two keywords. async marks a method that may pause; await pauses it without blocking a thread until a task finishes. The compiler rewrites your straightforward-looking method into a state machine that does all the bookkeeping. This lesson explains the idea, shows how to write and call async methods, and walks through the traps: async void, deadlocks from blocking, ConfigureAwait, and ValueTask.

Your first async method

An async method returns Task (no result), Task<T> (a result of type T), or, rarely, ValueTask/ValueTask<T>. By convention its name ends in Async. Inside, await unwraps a task: it gives you the T of a Task<T>.

C# An async method that awaits a 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.

Follow the numbers. The call runs synchronously up to the first await that has to wait, so "GreetAsync starts" prints inside the call. At the await, the method returns to its caller, handing back an incomplete Task<string>; the caller keeps going and prints line 2. A hundred milliseconds later the method resumes where it left off, prints line 3, and its return completes the task. The caller's own await pending then continues with the string.

Notice there is no thread sleeping during the delay. Nothing is blocked; the method is simply suspended.

What the compiler does: the state machine

You never see it, but understanding it removes the mystery. For each async method the compiler generates a small class (a state machine) holding the method's local variables and a number saying "which await am I waiting at?". When you hit an await on an incomplete task, the compiler-generated code:

  1. stores the current state and locals in that object,
  2. registers "run my MoveNext method when this task completes" as a continuation,
  3. returns to the caller.

When the awaited task finishes, MoveNext runs again, jumps to the right place using the state number, and carries on. If the awaited task has already finished by the time you reach await, the method does not pause at all and continues synchronously; that fast path is why await on a cached result costs almost nothing.

Two consequences are worth remembering. An async method runs on the calling thread until its first real suspension, and after a suspension it may resume on a different thread (the thread pool in a console app, the original thread in a UI app). And since the locals live in an object on the heap, async methods allocate; for extremely hot paths that is what ValueTask tries to avoid.

Sequential versus concurrent awaiting

await pauses this method, so two awaits in a row happen one after the other. To run operations concurrently, start both tasks first and await them afterwards.

C# One after the other, then at the same time

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 sequential version needs about 300 ms, the concurrent one about 150 ms. We print booleans instead of raw times because exact milliseconds differ on every run. For many tasks, use await Task.WhenAll(...), covered in WhenAll, WhenAny and Task.WhenEach.

Exceptions with await

Unlike Wait() and Result, await rethrows the original exception, so ordinary try/catch works exactly as in synchronous code.

C# try/catch around await

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 exception is thrown inside the async method after the suspension, stored in the task, and rethrown at the caller's await. Because the stored exception lives in the task, an async method that throws before its first await still reports the error through the returned task and not as a direct throw. One exception to remember: argument validation in async methods is deferred too, so a bad argument may only surface when you await. Libraries often split the method in two (a normal wrapper that validates, then an inner async method) to throw early.

The async void trap

An async method can return void. It exists for one reason: event handlers, whose signature is fixed as void. In every other situation it is a bug waiting to happen, because the caller has no task to await or to ask about errors. An exception thrown after the first await in an async void method is raised on the synchronization context or thread pool, and in most hosts it crashes the process. You cannot catch it at the call site.

C# async void cannot be awaited (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 compiler stops you with main.cs(1,1): error CS4008: Cannot await 'void'. Calling FailVoidAsync(); without await compiles, but the exception later takes down the process, and the caller cannot catch it. The Task version is safe, because the caller can await it and catch the original exception:

C# The Task version reports its error to the caller

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.

Rule: return Task, never void, unless you are writing an event handler.

async Main

The entry point itself may be async. Top-level statements can use await directly (as the examples here do), and an explicit Main can return Task or Task<int>.

C#
// Read-only: the explicit form of what top-level await expands to.
static async Task<int> Main(string[] args)
{
    await Task.Delay(10);
    Console.WriteLine("done");
    return 0;   // process exit code
}

The runtime waits for the returned task before exiting, and an unhandled exception ends the process with a non-zero exit code. See Program Structure.

Sync-over-async and deadlocks

Calling .Result or .Wait() on a task from a thread that has a synchronization context (a UI thread, or classic ASP.NET request thread) can freeze the program forever. Here is why. The UI thread blocks waiting for the task. The task's await wants to resume on the UI thread (the captured context), but that thread is busy blocking. Each waits for the other.

Console apps and ASP.NET Core have no such context, so the same code merely wastes a thread instead of deadlocking, which makes the bug easy to miss until you move the code into a UI or library. The remedies are, in order of preference:

  1. Go async all the way: make the caller async and await.
  2. If you truly must block at a boundary, do it at the very top of the program, not deep inside.
  3. Libraries can use ConfigureAwait(false) (below) so they do not need the original context.

We cannot show a real deadlock here because a console program has no context to deadlock on, but here is the shape of the bad code:

C#
// Read-only: do not do this in UI or old ASP.NET code.
string Load()
{
    return LoadAsync().Result;   // blocks the UI thread; LoadAsync wants it back -> deadlock
}

ConfigureAwait

By default, await captures the current SynchronizationContext (or task scheduler) and resumes there. That is what you want in UI code, where you must touch controls on the UI thread. In library code it is usually unnecessary and costs a little, so libraries commonly write await task.ConfigureAwait(false), meaning "I do not care which thread I resume on".

C# ConfigureAwait in an application library method

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 ASP.NET Core application code (controllers, minimal APIs) there is no context, so ConfigureAwait(false) makes no difference and most teams leave it out. In a reusable library, or in UI projects' non-UI layers, add it to every await. Do not use it in code that touches UI controls after the await.

ValueTask

Every Task<T> is a heap object. If a method very often has its answer ready (a cache hit, a buffered read), allocating a task for every call wastes memory. ValueTask<T> is a struct that either holds the result directly or wraps a real task.

C# A cache-friendly method returning ValueTask

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 second request for tea completes synchronously with no task allocation. The trade-off is strict usage rules: await a ValueTask once, never store it for later or await it twice, and never call .Result before it has completed. If you need to use it more than once, convert it with .AsTask(). Default to Task<T>; choose ValueTask<T> only for measured hot paths with frequent synchronous completion.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does await do when the awaited task has not finished yet?

    The method is suspended and registered as a continuation. The thread is free to do other work.
  2. 2. Why should you avoid async void methods (except event handlers)?

    There is no Task to observe, so errors escape to the context or thread pool.
  3. 3. What exception do you catch when an awaited task fails with a FormatException?

    await unwraps the stored exception and rethrows the original one.
  4. 4. Why can .Result deadlock in a UI application?

    The blocked thread is the one the continuation needs, so both wait forever.
  5. 5. How many times may you safely await the same ValueTask<T> instance?

    A ValueTask may be backed by a reused object. Await it once, or call AsTask() to get a normal task.

Summary

  • async methods return Task, Task<T> or ValueTask<T>; await suspends the method without blocking a thread and resumes when the task completes.
  • The compiler turns an async method into a state machine; if the awaited task is already done, no suspension happens.
  • Sequential awaits run one after another; start tasks first and await later (or Task.WhenAll) for concurrency.
  • await rethrows the original exception, so normal try/catch works.
  • Never use async void outside event handlers. Go async all the way, and avoid .Result and .Wait().
  • Libraries use ConfigureAwait(false); ValueTask<T> is for hot paths with frequent synchronous results and must be awaited only once.

Next: WhenAll, WhenAny and Task.WhenEach