async / await (C#)

async and await let C# run long operations — like web requests or file reads — without blocking the program, keeping apps responsive. await pauses a method until an awaited task finishes, then continues.

C#

You mark a method async and have it return a Task (or Task<T> for a result). Inside, you await operations that return tasks, and the method resumes automatically when they complete.

While awaiting, the thread is free to do other work instead of sitting idle, which is what makes async code efficient. Most async method names end with 'Async' by convention.

Syntax

async Task<T> NameAsync() { var x = await SomethingAsync(); }

Examples

C#

async Task<int> GetNumberAsync()
{
    await Task.Delay(100);
    return 42;
}

int result = await GetNumberAsync();
Console.WriteLine(result);

Output:

42

Learn it in a lesson

See also

Back to the Dictionary