Skip to content
Happy Programming Guide
Start learning
C#

Asynchronous Programming with C#

What async and await actually do, why .Result deadlocks, how to run work concurrently with Task.WhenAll, and cancellation done properly.

Orange cat with orange eyes lying on a desk, looking right into the camera

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#

CSHARP
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#

CSHARP
// 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.

CSHARP
// 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:

CSHARP
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#

CSHARP
// 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.

CSHARP
// 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#

CSHARP
// 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:

CSHARP
private async void OnClick(object sender, EventArgs e)
{
    try
    {
        await DoWorkAsync();
    }
    catch (Exception ex)
    {
        _logger.LogError(ex, "Click handler failed");
    }
}

Cancellation#

CSHARP
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);
}
CSHARP
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:

CSHARP
[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:

CSHARP
foreach (var item in items)
{
    ct.ThrowIfCancellationRequested();
    await ProcessAsync(item, ct);
}

Exceptions#

CSHARP
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:

CSHARP
var task = Task.WhenAll(tasks);

try
{
    await task;
}
catch
{
    foreach (var ex in task.Exception!.InnerExceptions)
    {
        _logger.LogError(ex, "One task failed");
    }
}

ConfigureAwait#

CSHARP
// 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#

CSHARP
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#

Concurrency versus parallelism, and which you needRead next

Keep reading

C#

C# and ASP.NET Core

Building web applications and APIs with ASP.NET Core: minimal APIs, controllers, dependency injection, middleware, validation and configuration.

5 min read

C#

C# Security

The security work that matters in .NET applications: SQL injection, XSS, secrets, authentication, deserialization, randomness and dependency scanning.

5 min read

C#

C# Collections

List, Dictionary, HashSet, Queue and the read-only interfaces — which to choose, how they perform, and the mistakes that cause exceptions.

5 min read

Keep going — pick your next guide

The fastest way to improve is to read one guide, then build the thing it describes. Start with the basics, or jump straight to a project.

Ask a question or share what worked

Your email address will not be published. Required fields are marked *