19
Lesson 19 of 35 ยท OOP

Async / Await Programming

Asynchronous programming lets your application remain responsive while waiting for slow operations (file I/O, network calls, databases). C#'s async/await makes asynchronous code look almost identical to synchronous code.

async / await Basics

Mark a method async to enable await inside it. await yields control back to the caller while waiting for the awaited task to complete. Use Task as the return type (or Task<T> to return a value).

async basics AsyncBasics.cs
using System.Net.Http;

static async Task FetchAsync(string url)
{
    using var client = new HttpClient();
    string content = await client.GetStringAsync(url);
    return content[..200]; // first 200 chars
}

// Top-level await (C# 9+)
string result = await FetchAsync("https://example.com");
Console.WriteLine(result);

Task.WhenAll โ€” Parallel Awaiting

Use Task.WhenAll to start multiple async operations simultaneously and wait for all of them to finish. This is far faster than awaiting them one by one.

WhenAll WhenAll.cs
static async Task SlowAddAsync(int a, int b, int delayMs)
{
    await Task.Delay(delayMs);
    return a + b;
}

var t1 = SlowAddAsync(1, 2, 500);
var t2 = SlowAddAsync(3, 4, 300);
var t3 = SlowAddAsync(5, 6, 400);

int[] results = await Task.WhenAll(t1, t2, t3);
// Total wait โ‰ˆ 500 ms, not 1200 ms
Console.WriteLine(string.Join(", ", results)); // 3, 7, 11

CancellationToken

Pass a CancellationToken to async methods so they can be gracefully cancelled. This is essential for UI applications and web servers.

Cancellation Cancel.cs
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(2));
try
{
    await Task.Delay(5000, cts.Token); // will be cancelled after 2s
    Console.WriteLine("Done");
}
catch (OperationCanceledException)
{
    Console.WriteLine("Operation was cancelled.");
}