In a C# async method, what does await do when the awaited Task has not finished yet, and what does the caller get back?
answer
- synchronous until the first pause
- an incomplete awaitable
- control returns up the call stack
- the remainder becomes a continuation
- no thread parked on the wait
basics
~20 sWhen the awaited Task is still incomplete, await suspends the async method, hands an unfinished Task back to the caller, and runs the rest of the method later as a continuation. No thread is blocked during the wait.
solid answer
~40 sAn `async` method runs synchronously on the caller's thread until it reaches an `await` on an awaitable that is not yet complete. At that point `await` registers the rest of the method as a **continuation** and the method returns to its caller, handing back a `Task` or `Task<T>` that represents the unfinished work, so the caller is free to do something else or to await that task in turn. Nothing blocks while the HTTP response is in flight. When the awaited task completes, the continuation runs (in a console app on a thread-pool thread, in a UI app by default back on the UI thread) and `await` produces the result or rethrows the exception stored in the task. If the awaited task had already completed, `await` takes its result and carries on without suspending.
code
csharp · 15 linesConsole.WriteLine("1. caller: calling GetTemperatureAsync");
Task<int> pending = GetTemperatureAsync("Oslo");
Console.WriteLine($"3. caller: got a Task back, IsCompleted = {pending.IsCompleted}");
Console.WriteLine("4. caller: free to do other work while the request is in flight");
int celsius = await pending;
Console.WriteLine($"6. caller: resumed with {celsius} C");
static async Task<int> GetTemperatureAsync(string city)
{
Console.WriteLine($"2. {city}: sending the request (still on the caller's call stack)");
await Task.Delay(500); // stands in for an HTTP call to the weather service
Console.WriteLine($"5. {city}: response arrived, the rest of the method runs as a continuation");
return 7;
}go deeper
Recall the sequence: the method runs until an incomplete await, returns a Task to the caller, and finishes later as a continuation. Say clearly that the thread is not blocked.
Explain where the continuation runs in a console app versus a UI app, why an already-completed task causes no suspension, and that exceptions travel inside the task to the await.
Use the model to reason about real code: work done before the first await still runs on the caller's thread, and starting several calls before awaiting any of them lets them overlap.
Connect the mechanism to capacity: threads released during I/O waits are what let one process serve many concurrent calls, which is the case for adopting async in I/O-heavy code.
## Two keywords, two jobs C# splits asynchronous code between two keywords. - **`async`** is a modifier on a method, lambda or local function. It does not start a thread or make anything run in the background. It tells the compiler that the body may contain `await` and has the compiler build the task the method returns: a method declared `async Task<int>` writes `return 7;` and the caller receives a `Task<int>` that will eventually hold 7. - **`await`** is an operator applied to an awaitable, most often a `Task` or `Task<T>`. Microsoft's reference page for the operator puts it plainly: it suspends evaluation of the enclosing async method until the operation completes, and it does not block the thread that evaluates the method. A **task** is an object that represents an operation that may still be running. It records whether the operation has finished, and once it has, either its result or the exception it failed with. `Task` is the version without a result value; `Task<TResult>` carries one. ## Step by step through a weather call The console tool below asks a weather service for a temperature. `Task.Delay(500)` stands in for the HTTP call so the example runs offline. ```csharp Task<int> pending = GetTemperatureAsync("Oslo"); Console.WriteLine(pending.IsCompleted); // False int celsius = await pending; ``` Here is what happens, in order: 1. The caller invokes `GetTemperatureAsync`. The method body starts **synchronously, on the caller's thread**, exactly like an ordinary method call, so its first line runs before the call returns. 2. The method reaches `await Task.Delay(500)`. The delay has not finished, so `await` arranges for the **rest of the method** to run once the delay completes. That remainder is called the **continuation**. 3. The method **returns to its caller** at once, handing back a `Task<int>` whose `IsCompleted` is `false`. 4. The caller keeps running. It could start two more requests here, update a progress message, or await the task it just received. 5. Half a second later the delay completes and the continuation runs: the line after the `await` executes, `return 7;` stores 7 in the task, and the task is marked complete. 6. The caller's own `await pending` was itself a suspension point, so the caller now resumes with `celsius = 7`. The runnable version with numbered output is in the code example below; the numbers print in the order 1 to 6, which is the order described here. ## What the caller gets back | Method declares | Caller receives | `await` on it produces | |---|---|---| | `async Task<int>` | a `Task<int>` | the `int` the method returned | | `async Task` | a `Task` | nothing; it is used as a statement | | `async void` | nothing it can await | not awaitable at all | When the method suspends, the caller receives the task **at the first suspension**, not when the method finishes; a method that never suspends hands back a task that is already complete. If the method throws, the exception is stored in the task and rethrown at the caller's `await`, not at the call. ## Where the continuation runs Where the remainder of the method runs depends on the environment it was awaited in: - In a **console app**, which has no special synchronization context, the continuation runs on a **thread-pool thread**, which may differ from the thread that started the method. - In a **desktop app**, `await` by default captures the UI thread's context and posts the continuation back to the UI thread, which is why code after an `await` in a button handler may touch controls. The rules for that capture, and how it can deadlock, are covered with contexts and deadlocks. - If the awaited task was **already complete** when execution reached `await`, there is no suspension at all: `await` reads the result and the method simply continues on the same thread. How the compiler arranges that fast path is the subject of the lesson on the compiler's state machine. ## Readings that lose marks - "`await` blocks until the task finishes." It does the opposite: the thread is released for other work, which is the whole point of the feature. - "`async` moves the method to a background thread." The method runs on the caller's thread until its first incomplete `await`; a method with no such `await` runs to the end synchronously. - "The caller waits for the method to finish." The caller gets control back at the first suspension and only waits if it awaits the returned task. - "Each `await` creates a new thread." Waiting for a timer or a network response needs no thread; a thread is needed only to run the continuation once the operation has finished.
- What happens at an await whose Task has already completed?`await` checks completion first. If the task is already finished, the method does not suspend: `await` takes the result, or rethrows the stored exception, and the next line runs straight away on the same thread. A method whose every awaited task is already complete runs to its end synchronously and hands the caller a task that is already complete.
- Does marking a method async make it run on a background thread?No. `async` only allows `await` in the body and wraps the return value in a task. The body runs on the caller's thread until the first `await` on an incomplete task; CPU-heavy code before that point still occupies the caller's thread. To move CPU-bound work off a UI thread you call `Task.Run` explicitly.
- How does a console tool await at its entry point?Since C# 7.1 `Main` may be declared `static async Task Main()` or return `Task<int>` for an exit code. With top-level statements, using `await` in them makes the compiler generate an entry point that returns `Task`, and the runtime waits for that task before the process exits.
A counter that hands you a buzzer: you place the order, step aside so the next customer can order, and come back when the buzzer goes off. Nobody stands at the counter waiting, and you collect the food where the buzzer tells you.
- await blocks the current thread until the task has finished
- Marking a method async makes it run on a background thread
- The caller only gets control back once the async method has completed
- Every await starts a new thread for the rest of the method
- An exception thrown in an async Task method surfaces at the call itself