Async & Await
Lesson 12 • Expert Track
Write responsive, non-blocking applications with async/await and Task<T>.
What You'll Learn
- • Understand
async,await, andTask<T> - • Run multiple operations concurrently
- • Use
Task.WhenAllandTask.WhenAny - • Handle exceptions in async methods
- • Cancel long-running tasks with
CancellationToken
Real-World Analogy
Imagine making breakfast. Synchronous: toast bread, wait, then brew coffee, wait. Async: start the toaster AND the coffee machine, then do something else while both work. await is you checking if each is done — you're not standing there watching.
Running C# Locally: Install the .NET SDK or use dotnetfiddle.net.
async/await Basics
Mark a method with async and it can use await to pause until an operation completes — without blocking the thread. The method returns Task (for void) or Task<T> (for a value).
Async Breakfast — Parallel Tasks
Run toast and coffee tasks concurrently with async/await.
using System;
using System.Threading.Tasks;
class Program
{
// async method returns Task (void) or Task<T> (with value)
static async Task Main()
{
Console.WriteLine("☕ Starting breakfast...");
// Start tasks concurrently
Task<string> toastTask = MakeToastAsync();
Task<string> coffeeTask = MakeCoffeeAsync();
// await both — they run in parallel!
string toast = await toastTask;
string coffee = await coffeeTask;
Console
...Task.WhenAll & Task.WhenAny
Task.WhenAll waits for every task to finish — perfect for batch operations. Task.WhenAny returns the first to complete — great for racing servers or implementing timeouts.
WhenAll & WhenAny — Concurrent Operations
Download files in parallel and race between servers.
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
class Program
{
static async Task Main()
{
Console.WriteLine("📦 Downloading files...");
// Start all downloads simultaneously
var tasks = new List<Task<string>>
{
DownloadFileAsync("report.pdf", 1500),
DownloadFileAsync("photo.jpg", 800),
DownloadFileAsync("data.csv", 2000),
DownloadFileAsync("video.mp4", 3000)
};
...Common Mistakes
- • Using
async void: Only useasync voidfor event handlers. Always returnTaskorTask<T>. - • Blocking with
.Result: Never calltask.Resultortask.Wait()— it can deadlock. Always useawait. - • Forgetting await: Without
await, exceptions are silently swallowed and the task runs fire-and-forget.
Exception Handling & Cancellation
Exceptions in async code work with regular try-catch. For long-running operations, pass a CancellationToken so callers can cancel gracefully.
Async Exceptions & Cancellation
Handle errors and cancel operations with CancellationToken.
using System;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
// Handling exceptions in async code
try
{
string result = await FetchDataAsync("https://api.example.com");
Console.WriteLine(result);
}
catch (HttpRequestException ex)
{
Console.WriteLine($"🌐 Network error: {ex.Message}");
}
catch (TimeoutException ex)
{
Console.WriteLine($"⏰ Timeo
...Pro Tips
- 💡 Start tasks early and
awaitthem late — maximise concurrency. - 💡 Always pass
CancellationTokento methods that accept it. - 💡 Use
ConfigureAwait(false)in library code to avoid deadlocks. - 💡 Suffix async methods with
Asyncby convention:GetDataAsync().
Lesson Complete! 🎉
You've mastered async programming in C#. Next: delegates, events, and event-driven architecture.
Sign up for free to track which lessons you've completed and get learning reminders.