Async & Await
Learn asynchronous programming in C# with async, await, and Task, and why it matters for responsive applications.
Why Asynchronous Code?
Operations like network calls or database queries take time. Synchronous code blocks the entire thread while waiting; asynchronous code frees the thread to do other work — like handling another web request — while it waits.
Task and async/await
`Task` represents an operation that will complete in the future. Marking a method `async` lets you use `await` to pause until a Task completes, without blocking the calling thread.
static async Task<string> FetchDataAsync(){ await Task.Delay(1000); // simulates a network call return "Data received!";}
static async Task Main(){ Console.WriteLine("Starting..."); string result = await FetchDataAsync(); Console.WriteLine(result);}Click Run to see what this code prints.
Awaiting Multiple Tasks
`Task.WhenAll` runs multiple asynchronous operations concurrently and waits for all of them, which is far more efficient than awaiting each one sequentially.
static async Task Main(){ Task<string> task1 = FetchDataAsync(); Task<string> task2 = FetchDataAsync();
string[] results = await Task.WhenAll(task1, task2); Console.WriteLine($"Got {results.Length} results.");}Common Beginner Mistakes
Calling `.Result` or `.Wait()` on a Task can cause deadlocks in certain contexts (like ASP.NET). Always `await` instead.
Once a method is async, callers generally need to be async too — mixing sync and async carelessly leads to subtle bugs.
FAQs
Not necessarily — async is about not blocking a thread while waiting, which is different from parallelism. For CPU-bound parallel work, see the next lesson on multithreading.
Summary
- Async code frees the thread to do other work while waiting.
- Task represents a future result; async/await lets you work with it cleanly.
- Task.WhenAll runs independent async operations concurrently.