An async method can pause at an await and give its thread back until the work it is waiting for finishes. That is the whole idea: while a database query or an HTTP request is in flight, the thread serves other requests instead of sitting idle. This guide covers writing it correctly, and the three mistakes that cause deadlocks and lost exceptions.
The basics#
public async Task<string> GetTitleAsync(string url)
{
using var client = new HttpClient();
string html = await client.GetStringAsync(url); // thread released here
return html.Length + " characters";
}
// Calling it
string result = await GetTitleAsync("https://example.com");
Three rules cover the syntax. An async method returns Task or Task<T>. You can only await inside an async method. And the method name conventionally ends in Async.
What happens at the await: the method returns to its caller immediately, the thread goes back to the pool, and when the network work completes the rest of the method is scheduled to continue. No thread was blocked waiting.
Async is not the same as parallel#
// Sequential - total time is the sum
var a = await FetchAAsync(); // 1 second
var b = await FetchBAsync(); // 1 second
// 2 seconds
// Concurrent - total time is the slowest
var taskA = FetchAAsync(); // started
var taskB = FetchBAsync(); // also started
await Task.WhenAll(taskA, taskB);
var a = taskA.Result; // safe here - already complete
// 1 second
Awaiting immediately after each call is the most common performance mistake in async code. Start the tasks, then await them together.
// With results
var results = await Task.WhenAll(urls.Select(FetchAsync));
// First one to finish
var winner = await Task.WhenAny(taskA, taskB);
For many items, limit how many run at once:
using var limiter = new SemaphoreSlim(10);
var tasks = urls.Select(async url =>
{
await limiter.WaitAsync();
try { return await FetchAsync(url); }
finally { limiter.Release(); }
});
var all = await Task.WhenAll(tasks);
Firing ten thousand requests at once will exhaust connections and probably get you rate-limited.
The deadlock#
// Never do this
var result = GetDataAsync().Result;
GetDataAsync().Wait();
In contexts with a synchronisation context — classic ASP.NET, WPF, WinForms — the continuation after the await needs the original thread. That thread is blocked waiting for the result. Neither can proceed, and the application hangs with no exception and no log entry.
// Correct - await all the way up
public async Task<IActionResult> Index()
{
var data = await GetDataAsync();
return View(data);
}
The phrase is “async all the way”. If a method calls async code, it should be async itself, and so should its caller, up to the framework entry point.
async void#
// Exceptions escape and crash the process
public async void SaveData()
{
await _repository.SaveAsync();
}
// Correct
public async Task SaveDataAsync()
{
await _repository.SaveAsync();
}
An async void method returns nothing to await, so the caller cannot know when it finished or catch what it threw. The exception surfaces on the thread pool and takes the process down.
The one legitimate use is an event handler, whose signature you cannot change. Keep those short and wrap the body:
private async void OnClick(object sender, EventArgs e)
{
try
{
await DoWorkAsync();
}
catch (Exception ex)
{
_logger.LogError(ex, "Click handler failed");
}
}
Cancellation#
public async Task<string> FetchAsync(string url, CancellationToken ct = default)
{
using var response = await _client.GetAsync(url, ct);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync(ct);
}
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
try
{
var result = await FetchAsync(url, cts.Token);
}
catch (OperationCanceledException)
{
Console.WriteLine("Timed out");
}
Accept a CancellationToken in every public async method and pass it down. Without that chain, a cancelled request keeps consuming resources until it finishes anyway.
In ASP.NET Core, the request’s token is supplied automatically:
[HttpGet]
public async Task<IActionResult> Get(CancellationToken ct)
{
var data = await _service.LoadAsync(ct); // cancelled if the client disconnects
return Ok(data);
}
For long-running loops, check the token yourself:
foreach (var item in items)
{
ct.ThrowIfCancellationRequested();
await ProcessAsync(item, ct);
}
Exceptions#
try
{
await FetchAsync(url);
}
catch (HttpRequestException ex)
{
_logger.LogError(ex, "Request failed");
}
With Task.WhenAll, several tasks can fail but only the first exception is rethrown. To see them all:
var task = Task.WhenAll(tasks);
try
{
await task;
}
catch
{
foreach (var ex in task.Exception!.InnerExceptions)
{
_logger.LogError(ex, "One task failed");
}
}
ConfigureAwait#
// In library code
var data = await FetchAsync().ConfigureAwait(false);
This says the continuation does not need the original context, which avoids a deadlock if a caller blocks and is marginally faster. Use it throughout library code.
In application code it is unnecessary — ASP.NET Core has no context, and in a desktop application you usually want to return to the UI thread so you can update controls.
Async streams#
public async IAsyncEnumerable<Order> StreamOrdersAsync(
[EnumeratorCancellation] CancellationToken ct = default)
{
await foreach (var row in _db.QueryAsync(ct))
{
yield return Map(row);
}
}
await foreach (var order in StreamOrdersAsync(ct))
{
Process(order);
}
This processes results as they arrive instead of loading everything first — the right shape for large result sets.
A quick reference#
| Do | Not |
|---|---|
await task |
task.Result, task.Wait() |
async Task |
async void, except event handlers |
Task.WhenAll for independent work |
awaiting each in turn |
Task.Delay |
Thread.Sleep in async code |
| Pass a CancellationToken down | ignoring cancellation |
A single shared HttpClient |
a new one per request |
Questions people ask#
Does async make my code faster?
Not the individual operation. It improves throughput, because threads are not blocked waiting, so a server handles more concurrent requests with the same resources.
Should everything be async?
Anything doing I/O — network, database, files. Pure computation gains nothing and adds overhead; for CPU work use Task.Run or the parallel APIs instead.
What is the difference between Task and ValueTask?
ValueTask avoids an allocation when the result is already available. Worth it only in hot paths that usually complete synchronously; elsewhere Task is simpler and has fewer rules.
Why does my async method run synchronously?
If it contains no await, it runs straight through and the compiler warns about it. Either add the await or make it a normal method returning a completed task.
Where to go next#
- C# advanced language features — async alongside LINQ and records.
- C# performance optimization — where the concurrency win shows up.
- Concurrency and multithreading — the concepts underneath.