Skip to content
Tutorials Center
My learning

Topics

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.

C#
static async Task<int> CountAsync()
{
    await Task.Delay(10);
    return 42;
}

Try it

C# Awaiting and combining tasks

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.

C# Exceptions and cancellation

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

C#
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 await of an incomplete task.
  • Do not block. task.Result and task.Wait() can deadlock under a single-threaded synchronization context (UI frameworks, older ASP.NET) and wrap exceptions in AggregateException. Use await all the way up. A Main method can be async 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. await itself runs nothing in parallel: start several tasks first, then await Task.WhenAll(...). CPU-heavy work belongs in Task.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, out or in parameters, and no ref struct locals that live across an await.
  • ValueTask avoids an allocation when the result is often available synchronously; await it only once.
  • Cancellation is cooperative: pass a CancellationToken and let OperationCanceledException flow.