C# Reference ยท Keywords and Statements
async and await
Reference for C# async and await: write asynchronous methods, return Task, Task<T> or ValueTask, handle exceptions and avoid common deadlocks.
async marks a method, lambda or anonymous method as asynchronous. Inside it you can use await to wait for an operation to finish without blocking the calling thread. The compiler rewrites the method into a state machine: at each await that is not yet complete, the method returns to its caller and resumes later, usually on a thread-pool thread or on the captured synchronization context.
An async method normally returns Task, Task<T>, ValueTask or ValueTask<T>. Async void exists for event handlers only. Async methods that return IAsyncEnumerable<T> or IAsyncEnumerator<T> can also yield return.
static async Task<int> CountAsync() { await Task.Delay(10); return 42; }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
async Task M() { ... } async Task<T> M() { ... return value; } async ValueTask<T> M() { ... } async void Handler(object? s, EventArgs e) { ... } // event handlers only async IAsyncEnumerable<T> M() { ... yield return x; } var f = async (int n) => { await Task.Delay(n); return n; }; // async lambda T r = await expression; // expression must be awaitable await foreach (var x in source) // IAsyncEnumerable<T> await using var d = resource; // IAsyncDisposable
Awaitable: anything with a GetAwaiter() method that returns an awaiter (Task, ValueTask, and your own types).
Returns: the caller receives a task that completes when the method body finishes. A return value; sets the result; an exception stored in the task is rethrown at the await.
Errors: an exception thrown in an async Task method does not escape at the call. It is stored in the task and rethrown when it is awaited. In an async void method it is raised on the synchronization context and usually crashes the process.
Usage notes
- Synchronous start: an async method runs synchronously until the first
awaitof an incomplete task. - Do not block.
task.Resultandtask.Wait()can deadlock under a single-threaded synchronization context (UI frameworks, older ASP.NET) and wrap exceptions inAggregateException. Useawaitall the way up. AMainmethod can beasync Task Main. ConfigureAwait(false)in library code skips capturing the context. ASP.NET Core and console apps have no context, so it makes no difference there.- Concurrency is not parallelism.
awaititself runs nothing in parallel: start several tasks first, thenawait Task.WhenAll(...). CPU-heavy work belongs inTask.Run. - Do not make fire-and-forget by accident. A task you neither await nor store hides failures. The compiler warns (CS4014) for a call inside an async method.
- No
ref,outorinparameters, and noref structlocals that live across anawait. ValueTaskavoids an allocation when the result is often available synchronously; await it only once.- Cancellation is cooperative: pass a
CancellationTokenand letOperationCanceledExceptionflow.
Related
kw-delegateandkw-eventop-lambda- Tutorials: async and await, Async pitfalls, Cancellation, Async streams