ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

C# Tutorial• 7 min read

Asynchronous Programming: async, await & Task

Non-blocking I/O, Task<T>, Task.WhenAll, and CancellationToken

Modern C# uses the Task-based Asynchronous Pattern (TAP) with async and await to perform scalable non-blocking I/O operations without tying up thread pool threads.

The Task Asynchronous Pattern

Task: Represents an asynchronous operation with no return value (void equivalent).

Task<T>: Represents an asynchronous operation returning a value of type T.

await: Yields thread execution back to the pool until the awaited I/O task completes.

Task.WhenAll(t1, t2): Executes multiple asynchronous tasks concurrently in parallel.

Concurrent Asynchronous Data Fetching
public async Task<string> DownloadReportAsync(string url) {
    using var client = new HttpClient();
    Console.WriteLine($"Initiating download from {url}...");
    // Await releases worker thread back to thread pool during network wait!
    string content = await client.GetStringAsync(url);
    return content;
}

// Parallel execution with Task.WhenAll
var task1 = DownloadReportAsync("https://api.site.com/q1");
var task2 = DownloadReportAsync("https://api.site.com/q2");
await Task.WhenAll(task1, task2);
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Which method should you use to run multiple independent asynchronous tasks concurrently and wait for all of them to finish?