async and await
await does not block the thread. It pauses the method, hands control back to the caller, and resumes when the work finishes.
Watch it animatedStep through it, with the running line highlighted. Free with an account.The idea
An async method runs like a normal method until it awaits something that is not finished. At that point it returns an incomplete Task to its caller. When the awaited work completes, the rest of the method is scheduled to continue.
Code
async Task<string> GetAsync() {
Console.WriteLine("A");
string data = await http.GetStringAsync(url);
Console.WriteLine("C");
return data;
}
Task<string> task = GetAsync();
Console.WriteLine("B"); // runs while the request is in flight
string result = await task;Tips
- Nothing is waiting on a thread during the request. That is why one server thread can handle many requests.
- Calling .Result or .Wait() blocks the thread instead and can deadlock. Use await all the way up.
In the .NET library
The compiler rewrites every async method into a state machine. In ASP.NET Core, awaiting I/O returns the thread to the pool until the response arrives.