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.

Time non-blockingSpace one state machineCode C#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

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;
public class Main {
    static CompletableFuture<String> getAsync() {
        System.out.println("A");
        return httpGetStringAsync(url)
            .thenApply(data -> {
                System.out.println("C");
                return data;
            });
    }

    public static void main(String[] args) {
        CompletableFuture<String> task = getAsync();
        System.out.println("B");   // runs while the request is in flight
        String result = task.join();   // Java has no await: join waits for the result
    }
}
string getData() {
    cout << "A\n";
    string data = httpGetString(url);   // C++17 has no await: this blocks the worker thread
    cout << "C\n";
    return data;
}

int main() {
    future<string> task = async(launch::async, getData);
    cout << "B\n";   // runs while the request is in flight
    string result = task.get();
}
import asyncio

async def get_async() -> str:
    print("A")
    data = await http_get_string(url)
    print("C")
    return data

async def main() -> None:
    task = asyncio.create_task(get_async())  # starts at main's next await
    print("B")  # prints before A here: the task runs once main awaits
    result = await task

Tips

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.