What is async/await in C# and how does it work?
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.
// 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;
}
await is hit, control returns to the callerawait// 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;
// ❌ 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