What is async/await in C# and how does it work?

What is async/await in C# and how does it work?

What is async/await in C# and how does it work?

Question

What is async/await in C# and how does it work?

Answer

async/await is a compiler feature that transforms asynchronous code into a state machine, allowing you to write non-blocking code in a familiar, sequential style.

Basic Syntax

// async method must return Task, Task<T>, or void (avoid void except for event handlers)
public async Task<string> FetchUserNameAsync(int id)
{
    // await suspends the method and releases the thread until the task completes
    var user = await _repository.FindAsync(id);
    return user.Name;
}

How it Works

  1. When await is hit, control returns to the caller
  2. The thread is free to do other work (serve other requests, etc.)
  3. When the awaited task completes, execution resumes after the await

Running Tasks in Parallel

// Sequential — 2 seconds total
var user    = await GetUserAsync();
var orders  = await GetOrdersAsync();

// Parallel — ~1 second total
var userTask   = GetUserAsync();
var orderTask  = GetOrdersAsync();
await Task.WhenAll(userTask, orderTask);
var user   = userTask.Result;
var orders = orderTask.Result;

Common Pitfalls

// ❌ Blocking — can cause deadlocks
var result = GetDataAsync().Result;

// ✅ Always await
var result = await GetDataAsync();

// ❌ async void — exceptions are unobservable
async void DoWork() { }

// ✅ async Task
async Task DoWork() { }
All Comments