Async and Await: Asynchronous Programming in C#
The Waiting Problem
Many operations spend most of their time waiting: a web request, a file read, a database query. If your code waits blocking the thread, the whole app freezes, or a web server cannot serve other users.
Simple example: A cook who puts a pot on the stove does not stare at it for 20 minutes. He starts chopping vegetables and returns when the water boils.
async and await let your code do the same.
The Basic Pattern
csharp
async Task<string> DownloadAsync(string url)
{
using var client = new HttpClient();
string html = await client.GetStringAsync(url); // waits WITHOUT blocking the thread
return html;
}
string page = await DownloadAsync("https://example.com");
Console.WriteLine(page.Length);
| Keyword | Meaning |
|---|---|
async | Marks a method that can use await |
await | Pause here until the task finishes, then continue |
Task | An operation that will finish later (no result) |
Task<T> | An operation that will finish later and give a T |
By convention, async methods end with the word Async.
Simulating Slow Work
csharp
async Task<int> GetPriceAsync()
{
await Task.Delay(1000); // pretend a slow service
return 42;
}
Console.WriteLine("Start");
int price = await GetPriceAsync();
Console.WriteLine($"Price {price}");
Run Several Tasks at the Same Time
csharp
using System.Diagnostics;
async Task<string> SlowAsync(string name, int ms)
{
await Task.Delay(ms);
return name;
}
var watch = Stopwatch.StartNew();
Task<string> a = SlowAsync("A", 1000); // starts immediately
Task<string> b = SlowAsync("B", 1000);
string[] results = await Task.WhenAll(a, b);
Console.WriteLine($"{string.Join(",", results)} in {watch.ElapsedMilliseconds} ms"); // about 1000 ms, not 2000
Cancellation
csharp
async Task WorkAsync(CancellationToken token)
{
for (int i = 1; i <= 10; i++)
{
token.ThrowIfCancellationRequested();
await Task.Delay(500, token);
Console.WriteLine($"Step {i}");
}
}
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(2));
try
{
await WorkAsync(cts.Token);
}
catch (OperationCanceledException)
{
Console.WriteLine("Cancelled");
}
Exceptions
Exceptions in async methods are thrown at the await, so a normal try/catch works:
csharp
try
{
await new HttpClient().GetStringAsync("https://invalid.example");
}
catch (HttpRequestException ex)
{
Console.WriteLine($"Request failed: {ex.Message}");
}
Common Mistakes
| Mistake | Why it is bad | Fix |
|---|---|---|
.Result or .Wait() | Blocks the thread and can deadlock | Use await |
async void | Exceptions cannot be caught | Use async Task (only event handlers may use async void) |
Forgetting await | Code runs on without waiting, errors are lost | Always await or store the task on purpose |
Creating new HttpClient() per request in a busy app | Wastes sockets | Reuse one, or use IHttpClientFactory in ASP.NET |
Task.Run for I/O waiting | Not needed | Async I/O already does not block |
Rule of thumb:
async/await is for waiting (I/O). For heavy calculation on many CPU cores, use Parallel and Task.Run (next lesson).
Conclusion
Use async and await for anything that waits, run independent tasks together with Task.WhenAll, support CancellationToken and never block with .Result.
Quick Summary: async Task methods, await to wait without blocking, WhenAll to run together.

