14. Async and Await
Asynchronous code lets a program keep working while it waits for slow operations such as web requests, files, databases or timers. In a web app it frees the thread to serve other requests; in a desktop or mobile app it keeps the screen responsive. Mark a method async, return Task (nothing) or Task<T> (a result), and use await to wait for a task without blocking the thread. When the awaited work finishes, the method continues where it left off. By convention async methods end with Async (GetUsersAsync).
A Task represents work in progress. Task.Delay is the async version of Thread.Sleep, Task.Run moves CPU-heavy work to a background thread, Task.WhenAll waits for several tasks at once (running them concurrently), and Task.WhenAny finishes when the first completes. Exceptions thrown inside an async method are captured and rethrown at the await, so normal try/catch works. A CancellationToken lets the caller cancel work, and await foreach with IAsyncEnumerable<T> consumes a stream of results as they arrive.
Async is about waiting efficiently (I/O-bound work), not about making calculations faster. Await all the way up the call chain: avoid .Result and .Wait(), which block the thread and can deadlock. The .NET libraries offer async versions of most I/O: File.ReadAllTextAsync, StreamReader.ReadLineAsync, HttpClient.GetStringAsync, and Entity Framework's ToListAsync.
- async method
- Sequential vs concurrent with Task.WhenAll
- Task.WhenAny and starting tasks first
- Task.Run for CPU-bound work
- Exceptions in async methods
- Cancellation with CancellationToken
- Async file reading and writing
- Streaming results with await foreach
- Processing a list concurrently
- Calling a web API with HttpClient
Key points to remember
- Return Task or Task<T>, not void. async void is only for event handlers, because its exceptions cannot be caught by the caller.
- Forgetting await runs the method without waiting and you get a Task instead of the result (the compiler warns).
- Run independent operations together: start the tasks first, then await Task.WhenAll(...); awaiting one after another runs them sequentially.
- I/O-bound work (network, disk, database) should use async APIs. CPU-bound work can use Task.Run, but in ASP.NET Core avoid Task.Run for request work.
- Top-level programs and Main can be async (static async Task Main()). ASP.NET Core controllers and minimal API handlers can return Task<IActionResult>.
- Pass a CancellationToken through your async methods so long operations can stop when the user cancels or the request ends.
- await in a loop is sequential. To process items concurrently, create a list of tasks and await Task.WhenAll.
- A method marked async with no await runs synchronously and the compiler warns.
Example 1: async method
static async Task<int> GetNumberAsync()
{
await Task.Delay(500); // simulates slow work
return 42;
}
int n = await GetNumberAsync();
Console.WriteLine("Result: " + n);
Show output
OutputResult: 42
Example 2: Sequential vs concurrent with Task.WhenAll
using System.Diagnostics;
static async Task<int> SlowSquareAsync(int n)
{
await Task.Delay(1000);
return n * n;
}
var sw = Stopwatch.StartNew();
int a = await SlowSquareAsync(2);
int b = await SlowSquareAsync(3); // starts only after the first ends
Console.WriteLine($"Sequential: {a + b} in about {sw.Elapsed.TotalSeconds:F0}s");
sw.Restart();
int[] results = await Task.WhenAll(SlowSquareAsync(2), SlowSquareAsync(3));
Console.WriteLine($"Concurrent: {results.Sum()} in about {sw.Elapsed.TotalSeconds:F0}s");
Show output
OutputSequential: 13 in about 2s Concurrent: 13 in about 1s
Example 3: Task.WhenAny and starting tasks first
static async Task<string> AfterAsync(int ms, string name)
{
await Task.Delay(ms);
return name;
}
Task<string> slow = AfterAsync(300, "slow"); // both start immediately
Task<string> fast = AfterAsync(100, "fast");
Task<string> winner = await Task.WhenAny(slow, fast);
Console.WriteLine(await winner);
Console.WriteLine(await slow); // wait for the other one too
Show output
Outputfast slow
Example 4: Task.Run for CPU-bound work
int total = await Task.Run(() => Enumerable.Range(1, 100).Sum()); Console.WriteLine(total); Task<string> upper = Task.Run(() => "background".ToUpper()); Console.WriteLine(await upper);
Show output
Output5050 BACKGROUND
Example 5: Exceptions in async methods
static async Task FailAsync()
{
await Task.Delay(100);
throw new InvalidOperationException("Something failed");
}
try
{
await FailAsync(); // the exception surfaces at the await
}
catch (InvalidOperationException ex)
{
Console.WriteLine("Caught: " + ex.Message);
}
Show output
OutputCaught: Something failed
Example 6: Cancellation with CancellationToken
using var cts = new CancellationTokenSource(500); // cancel after 0.5 seconds
try
{
await Task.Delay(5000, cts.Token);
Console.WriteLine("Finished");
}
catch (OperationCanceledException)
{
Console.WriteLine("Cancelled after timeout");
}
Show output
OutputCancelled after timeout
Example 7: Async file reading and writing
await File.WriteAllTextAsync("note.txt", "Hello async");
string text = await File.ReadAllTextAsync("note.txt");
Console.WriteLine(text);
await File.AppendAllTextAsync("note.txt", "\nSecond line");
string[] lines = await File.ReadAllLinesAsync("note.txt");
Console.WriteLine(lines.Length);
Show output
OutputHello async 2
Example 8: Streaming results with await foreach
await foreach (int n in CountAsync(3))
Console.WriteLine("Got " + n);
static async IAsyncEnumerable<int> CountAsync(int max)
{
for (int i = 1; i <= max; i++)
{
await Task.Delay(100);
yield return i; // each value is delivered as soon as it is ready
}
}
Show output
OutputGot 1 Got 2 Got 3
Example 9: Processing a list concurrently
static async Task<string> DownloadAsync(string site)
{
await Task.Delay(200); // pretend to call the web
return $"{site}: done";
}
string[] sites = { "a.com", "b.com", "c.com" };
Task<string>[] tasks = sites.Select(DownloadAsync).ToArray(); // all start now
string[] results = await Task.WhenAll(tasks);
foreach (string r in results)
Console.WriteLine(r);
Show output
Outputa.com: done b.com: done c.com: done
Example 10: Calling a web API with HttpClient
// Needs an internet connection. Create one HttpClient and reuse it.
using var http = new HttpClient();
http.Timeout = TimeSpan.FromSeconds(10);
try
{
string html = await http.GetStringAsync("https://example.com");
Console.WriteLine(html.Contains("Example Domain"));
}
catch (HttpRequestException ex)
{
Console.WriteLine("Request failed: " + ex.Message);
}
Show output
OutputTrue