C# Async/Await
Many operations spend most of their time waiting: for a web server to respond, a file to be read, a database query to finish. Blocking a thread while waiting wastes resources and, in a desktop app, freezes the user interface. Asynchronous programming with async and await lets your code start such an operation, step aside while it runs, and continue when the result is ready — while still reading like ordinary top-to-bottom code.
Tasks
An asynchronous operation is represented by a Task (no result) or a Task<T> (a result of type T) from System.Threading.Tasks. A task is a promise of work that will complete in the future.
asyncmarks a method that usesawait. It usually returnsTaskorTask<T>.awaitpauses the method until the awaited task completes, without blocking the thread, then unwraps its result.
using System;
using System.Threading.Tasks;
Console.WriteLine("Ordering coffee...");
string coffee = await MakeCoffeeAsync("latte");
Console.WriteLine(quot;Got a {coffee}");
static async Task<string> MakeCoffeeAsync(string kind)
{
Console.WriteLine(quot; Brewing {kind}");
await Task.Delay(100); // simulate waiting for the machine
Console.WriteLine(quot; {kind} ready");
return kind;
}Ordering coffee...
Brewing latte
latte ready
Got a latte
Task.Delay is the asynchronous version of Thread.Sleep: it completes after the given number of milliseconds without tying up a thread. In real code you would await things like httpClient.GetStringAsync(url) or File.ReadAllTextAsync(path).
Top-level statements may use await directly. In a classic program, declare static async Task Main().
Running tasks concurrently
Awaiting tasks one after another runs them sequentially. If they are independent, start them all first and then await them together with Task.WhenAll. The total time becomes roughly the time of the slowest task instead of the sum.
using System;
using System.Diagnostics;
using System.Threading.Tasks;
static async Task<int> FetchAsync(string source, int delayMs, int value)
{
await Task.Delay(delayMs); // pretend this is a network call
return value;
}
var sw = Stopwatch.StartNew();
int a = await FetchAsync("users", 300, 10);
int b = await FetchAsync("orders", 300, 20);
int c = await FetchAsync("stock", 300, 30);
long sequentialMs = sw.ElapsedMilliseconds;
Console.WriteLine(quot;Sequential total: {a + b + c}");
sw.Restart();
Task<int> t1 = FetchAsync("users", 300, 10);
Task<int> t2 = FetchAsync("orders", 300, 20);
Task<int> t3 = FetchAsync("stock", 300, 30);
int[] results = await Task.WhenAll(t1, t2, t3);
long concurrentMs = sw.ElapsedMilliseconds;
Console.WriteLine(quot;Concurrent total: {results[0] + results[1] + results[2]}");
Console.WriteLine(quot;Sequential took over 0.8 s: {sequentialMs > 800}");
Console.WriteLine(quot;Concurrent was faster: {concurrentMs < sequentialMs}");Sequential total: 60
Concurrent total: 60
Sequential took over 0.8 s: True
Concurrent was faster: True
Task.WhenAll returns the results in the order the tasks were passed, regardless of which finished first — so the output is deterministic. (We print comparisons rather than exact timings, because timings vary from run to run.)
Exceptions in async code
An exception thrown inside an async method is stored in the task and re-thrown when you await it, so ordinary try/catch works:
using System;
using System.Threading.Tasks;
static async Task<decimal> GetPriceAsync(string sku)
{
await Task.Delay(50);
if (sku == "")
throw new ArgumentException("SKU must not be empty");
return 9.99m;
}
try
{
Console.WriteLine(await GetPriceAsync("A-1"));
Console.WriteLine(await GetPriceAsync(""));
}
catch (ArgumentException ex)
{
Console.WriteLine(quot;Failed: {ex.Message}");
}9.99
Failed: SKU must not be empty
Processing results as a pipeline
Async methods compose naturally. Each step awaits the previous one, and a loop can await inside each iteration:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
static async Task<string> DownloadAsync(int page)
{
await Task.Delay(20);
return quot;<page {page}>";
}
static async Task<List<string>> DownloadAllAsync(int pages)
{
var list = new List<string>();
for (int p = 1; p <= pages; p++)
{
string html = await DownloadAsync(p);
list.Add(html.ToUpper());
Console.WriteLine(quot;Downloaded page {p}");
}
return list;
}
List<string> all = await DownloadAllAsync(3);
Console.WriteLine(string.Join(" ", all));Downloaded page 1
Downloaded page 2
Downloaded page 3
<PAGE 1> <PAGE 2> <PAGE 3>
Rules of thumb
| Do | Avoid |
|---|---|
Name async methods with an Async suffix |
async void (except for UI event handlers) — exceptions cannot be caught |
Return Task / Task<T> and await it |
.Result or .Wait() — they block and can deadlock |
Use Task.WhenAll for independent work |
Awaiting independent tasks one by one when speed matters |
Pass a CancellationToken to long operations |
Wrapping CPU-bound work in async without Task.Run |
Note:
asyncdoes not automatically mean "runs on another thread". Awaiting I/O frees the thread while waiting; for heavy calculations, useTask.Run(() => …)to move the work off the current thread.
Test yourself
What does await do?
- Blocks the thread until the task completes
- Pauses the method until the task completes without blocking the thread
- Starts a new thread
- Cancels the task
What should an async method that produces an int return?
- int
- async int
- Task<int>
- void
In what order does await Task.WhenAll(t1, t2, t3) return results?
- Order of completion
- Random order
- The order the tasks were passed in
- Reverse order