Async and Await in C#: Practical Examples and Common Mistakes

async and await let a method wait for slow work, such as a network call, a database query or a file read, without blocking the thread it runs on. While the operation is in flight, the thread goes back to the pool (in a web app) or keeps the UI responsive (in a desktop app). When the result arrives, execution continues on the line after await.

The keywords arrived in C# 5 and .NET Framework 4.5. The examples below use current .NET and top-level statements, so you can paste them into a new console project and run them.

A first example

using var http = new HttpClient();

int size = await GetPageSizeAsync(http, "https://learn.microsoft.com/dotnet/");
Console.WriteLine($"Downloaded {size:N0} bytes");

static async Task<int> GetPageSizeAsync(HttpClient http, string url)
{
    byte[] body = await http.GetByteArrayAsync(url);
    return body.Length;
}

Three things to notice:

  • The method is marked async and returns Task<int>, not int. The caller gets a task right away and awaits it to obtain the number.
  • Inside the method, return body.Length; returns a plain int. The compiler wraps it in the task for you.
  • By convention, the method name ends in Async.

If a method has nothing to return, give it the return type Task. Use async void only for event handlers; more on that below.

Running several operations at once

Awaiting calls one after another runs them in sequence. If they do not depend on each other, start them all and await them together with Task.WhenAll:

using System.Diagnostics;

using var http = new HttpClient();

string[] urls =
[
    "https://learn.microsoft.com/dotnet/",
    "https://github.com/dotnet/runtime",
    "https://www.nuget.org/"
];

var timer = Stopwatch.StartNew();

int[] sizes = await Task.WhenAll(urls.Select(url => GetPageSizeAsync(http, url)));

Console.WriteLine($"{sizes.Sum():N0} bytes in {timer.ElapsedMilliseconds} ms");

The total time is roughly that of the slowest request rather than the sum of all three. Task.WhenAll returns the results in the same order as the input, regardless of which request finished first.

Cancelling and timeouts

Long-running async methods should accept a CancellationToken and pass it on to every call that supports one:

static async Task<int> GetPageSizeAsync(
    HttpClient http, string url, CancellationToken cancellationToken = default)
{
    byte[] body = await http.GetByteArrayAsync(url, cancellationToken);
    return body.Length;
}

The caller decides when to give up. A CancellationTokenSource created with a delay works as a timeout:

using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));

try
{
    int size = await GetPageSizeAsync(http, urls[0], cts.Token);
    Console.WriteLine($"Downloaded {size:N0} bytes");
}
catch (OperationCanceledException)
{
    Console.WriteLine("The request took longer than 5 seconds and was cancelled.");
}

In ASP.NET Core you rarely create the source yourself. Add a CancellationToken parameter to a controller action or minimal API handler and the framework cancels it when the client disconnects.

Mistakes worth avoiding

Blocking on a task with .Result or .Wait(). In a WinForms or WPF app, and in classic ASP.NET, this can deadlock: the blocked thread is the one the awaited code needs to resume on. Even where it does not deadlock, it ties up a thread for nothing. Make the calling method async instead, all the way up.

async void methods. The caller cannot await them, and an exception thrown inside one cannot be caught by the caller. It will usually crash the process. Event handlers such as button1_Click are the one legitimate use.

Forgetting to await. Calling SaveAsync() without await starts the work and moves on. Any exception it throws is lost, and the code after it may run before the save has finished. The compiler warns about this (CS4014); treat the warning as an error.

Wrapping synchronous code in Task.Run inside a library. Task.Run moves work to another thread. That is useful for keeping a UI responsive during CPU-heavy work, but in a library or a web app it only adds overhead. Expose a synchronous method and let the caller decide.

ConfigureAwait(false). In library code that does not touch UI controls or HttpContext, await task.ConfigureAwait(false) tells the runtime it may resume on any thread. Application code, including ASP.NET Core, does not need it.

Further reading

2 thoughts on “Async and Await in C#: Practical Examples and Common Mistakes”

Leave a Comment