async and await

async marks a method that may pause, and await is the pause: it gives the thread back to the caller until the awaited task finishes. This is not a thread per call and not a callback the programmer writes; the compiler turns the method into a state machine that resumes where it stopped.

What async and await do

Two calls to an async method start two waits before either finishes. Each method prints when it begins and when it ends, and the delays differ so that the order is not a race:

Console.WriteLine("start"); var first = Fetch(1, 40); var second = Fetch(2, 10); Console.WriteLine("both started"); await Task.WhenAll(first, second); Console.WriteLine($"first {first.Result} second {second.Result}"); Console.WriteLine("end"); static async Task<string> Fetch(int id, int delay) { Console.WriteLine($"fetch {id} begin"); await Task.Delay(delay); Console.WriteLine($"fetch {id} end"); return $"data{id}"; }

dotnet run

start
fetch 1 begin
fetch 2 begin
both started
fetch 2 end
fetch 1 end
first data1 second data2
end

Both methods began before the program printed both started, because the first await inside Fetch returned to its caller immediately. The one that waited ten milliseconds finished before the one that waited forty, although it was started second. A synchronous method would have printed its begin and end lines in pairs, one call after the other.

The order of the lines

await does not block the thread: it records where the method stopped and returns. That is why a program that starts a task and does not await it keeps running, and why the continuation runs later. A top-level program may use await directly, because the compiler generates an async entry point for it.

Console.WriteLine("a"); await Task.Delay(1); Console.WriteLine("b");

dotnet run

a
b

The two lines are in source order, and the point of the wait is invisible in the output: a delay of a millisecond does not print anything. What the state machine does show is that the thread was free between the two lines for other work, which is exactly what a server needs while a database answers.

The state of a task

A call to an async method returns a Task at its first await, and the status of that task says what it is doing:

var task = Work(); Console.WriteLine($"before {task.Status}"); await task; Console.WriteLine($"after {task.Status}"); static async Task Work() { await Task.Delay(10); }

dotnet run

before WaitingForActivation
after RanToCompletion

WaitingForActivation is the status of a task that is waiting on something outside itself, which is what Task.Delay gives. After the await the task is RanToCompletion, and a program that checks the status instead of awaiting sees an intermediate value that may change a moment later.

An exception from an async method

An exception thrown after an await is stored in the task and rethrown at the await of the caller, so a normal try around the await catches it. The stack trace of the rethrow starts at the await, not at the throw, which is the one thing that surprises a reader of a log:

try { await Fail(); } catch (InvalidOperationException e) { Console.WriteLine($"caught {e.Message}"); } Console.WriteLine("line after the catch"); static async Task Fail() { await Task.Delay(1); throw new InvalidOperationException("from the async method"); }

dotnet run

caught from the async method
line after the catch

The exception did not escape the method silently, because the task carries it; a task that is never awaited keeps the exception until it is observed or the process ends, which the next lesson shows. The comment in the exception text says where it came from, and the program continued after the catch.

Exercises

  1. Remove the await Task.WhenAll line and see which lines are missing from the output.
  2. Add a third fetch with a delay of 25 milliseconds and predict where its lines go.
  3. Print the status of a task after Task.WhenAll.
  4. Throw before the first await instead of after it and compare the stack trace.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does await do in an async method?

    Answer

    Gives the thread back until the task finishes, then continues

    The method returns to its caller at the await and resumes on a continuation.

  2. Which type does an async method with no return value have?

    Answer

    Task

    Task is the awaitable form of no value; async void exists but is reserved for handlers.

  3. What does this program print? var task = Work(); Console.WriteLine(task.Status); await task; static async Task Work() { await Task.Delay(1); }

    Answer

    WaitingForActivation

    The status is printed before the await, and the measured run showed WaitingForActivation.

  4. What does the status RanToCompletion mean?

    Answer

    The task finished successfully

    A faulted task is Faulted and a cancelled one is Canceled.

  5. What does this program print? Console.WriteLine("a"); await Task.Delay(1); Console.WriteLine("b");

    Answer

    a and then b

    The lines stay in source order and the compiler makes the entry point async.

  6. What does this program print? Console.WriteLine(await Task.FromResult(5));

    Answer

    5

    Awaiting a completed task gives its result.

  7. What happens to an exception thrown after an await in an awaited method?

    Answer

    It is rethrown at the await of the caller

    The task stores it and the await observes it, which is what the catch caught.

  8. Why is async not the same as multithreading?

    Answer

    It releases the thread while waiting instead of adding one

    The point of async I/O is that no thread waits during the operation.

  9. What does this program print? try { await Fail(); } catch (InvalidOperationException e) { Console.WriteLine(e.Message); } static async Task Fail() { await Task.Delay(1); throw new InvalidOperationException("boom"); }

    Answer

    boom

    The await rethrows inside the try, so the catch prints the message.

  10. What is a task whose result is never awaited?

    Answer

    It keeps its exception until it is observed or the process ends

    An unobserved task exception stays on the task, which the next lesson measures.

The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev