async / await
await does not wait. It returns, and arranges to be called back.
Before you start
await sounds like it means "wait here until this finishes". It doesn't. What it actually does is *return* from the current method, hand its remaining work to a callback, and let the caller keep going.
This is confusing until you see it. The thread doing your code isn't blocked while a database query runs; it's off doing other work. When the query returns, the runtime resumes your method from where the await left off.
This lesson traces what actually happens step by step — the state machine the compiler generates, the callback that fires on completion, and where async exceptions surface.
Stack
the thread pool thread currently runningEverything up to the first await runs like an ordinary method call.
Step 1 of 7. An async method starts synchronously. Calling `GetPageAsync` does not schedule anything on another thread. The body begins running immediately, on the caller's thread, and `"before"` is printed right away. `async` is not a synonym for "on a background thread". Nothing is parallel yet.
Step 01 / 07
An async method starts synchronously
Calling GetPageAsync does not schedule anything on another thread. The body begins running immediately, on the caller's thread, and "before" is printed right away.
async is not a synonym for "on a background thread". Nothing is parallel yet.
async Task<string> GetPageAsync(HttpClient http) { Console.WriteLine("before"); // runs on the caller's thread string body = await http.GetStringAsync(url); // returns here Console.WriteLine("after"); // resumes later return body.Trim();}var task = GetPageAsync(http); // starts it, does not waitDoSomethingElse(); // runs while the request is in flightstring page = await task; // now wait for the result// Blocking anti-pattern:string bad = GetPageAsync(http).Result; // can deadlock