Async Best Practices

Async Best Practices in C#: Every professional kitchen has a laminated card on the wall. Never leave a pan unattended.

The Analogy: The Laminated Rules by the Pass

Every professional kitchen has a laminated card on the wall. Never leave a pan unattended. Never carry more plates than you can set down. Call out when you are behind. Say "behind you" on the turn. None of it is clever. All of it is there because at some point someone got burned, and the rule is cheaper than the burn.

Async code has the same card. await is easy to write and the failure modes are all invisible: the deadlock that only happens in production, the retry storm that takes down the service you were retrying against, the five hundred sockets you opened because Select looked innocent. The previous lesson taught the mechanics. This one is the card on the wall — and the three helpers below are worth copying into every project you own.


Syntax or Core Structure

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

class Program
{
    static int calls;

    // 1. Retry with backoff. Note the token, and that the last attempt rethrows.
    static async Task<T> WithRetryAsync<T>(Func<int, Task<T>> action, int attempts, CancellationToken token)
    {
        for (int attempt = 1; ; attempt++)
        {
            try { return await action(attempt); }
            catch (Exception) when (attempt < attempts)
            {
                await Task.Delay(50 * attempt, token);      // back off; do not hammer
            }
        }
    }

    // 2. A per-call deadline that composes with the caller's token.
    static async Task<T> WithTimeoutAsync<T>(Func<CancellationToken, Task<T>> action,
                                             TimeSpan limit, CancellationToken token)
    {
        using var linked = CancellationTokenSource.CreateLinkedTokenSource(token);
        linked.CancelAfter(limit);
        return await action(linked.Token);
    }

    // 3. Throttled fan-out, so 500 items do not become 500 open sockets.
    static async Task<TResult[]> ForEachAsync<TSource, TResult>(
        IEnumerable<TSource> source, int limit, Func<TSource, Task<TResult>> body)
    {
        using var gate = new SemaphoreSlim(limit);

        async Task<TResult> RunAsync(TSource item)
        {
            await gate.WaitAsync();
            try { return await body(item); }
            finally { gate.Release(); }                     // release in finally, always
        }

        return await Task.WhenAll(source.Select(RunAsync));
    }

    static async Task<int> LoadAsync(int id, int attempt, CancellationToken token)
    {
        Interlocked.Increment(ref calls);                   // ++calls would be a data race
        await Task.Delay(20, token);
        if (id == 3 && attempt < 3) throw new TimeoutException("transient");
        return id * 10;
    }

    static async Task<int> SlowAsync(CancellationToken token)
    {
        await Task.Delay(5000, token);
        return 0;
    }

    static async Task Main()
    {
        int[] ids = { 1, 2, 3, 4 };

        int[] results = await ForEachAsync(ids, limit: 2, body: id =>
            WithRetryAsync(attempt => LoadAsync(id, attempt, CancellationToken.None),
                           attempts: 3, CancellationToken.None));

        Console.WriteLine($"results: {string.Join(", ", results)}");
        Console.WriteLine($"calls made: {calls} for {ids.Length} ids");

        try
        {
            await WithTimeoutAsync(SlowAsync, TimeSpan.FromMilliseconds(100), CancellationToken.None);
        }
        catch (OperationCanceledException)
        {
            Console.WriteLine("slow call abandoned after 100ms");
        }
    }
}

Output:

results: 10, 20, 30, 40
calls made: 6 for 4 ids
slow call abandoned after 100ms

Six calls for four ids: id 3 failed twice before succeeding, and WithRetryAsync absorbed both failures without the caller knowing. Task.WhenAll returned the results in input order even though they finished out of order, and the semaphore meant only two were ever in flight. The finally { gate.Release(); } is not decoration — miss it once on an exception path and the gate leaks a permit per failure until everything hangs forever.


Technical Depth: The Card on the Wall, Rule by Rule

The rules, and what each one prevents

RuleWhat goes wrong without it
Never .Result / .Wait()deadlock on a UI or classic ASP.NET context; AggregateException wrapping
async Task, never async voidthe exception escapes to nowhere and can kill the process
Pass CancellationToken everywherea cancelled request keeps burning a connection for 30 more seconds
Throttle the fan-out500 concurrent calls, exhausted connection pool, throttled dependency
Back off between retriesa struggling service gets a retry storm and never recovers
Deadline every network callone slow dependency pins every request thread you have
Task.Delay, never Thread.Sleepa pool thread blocked doing absolutely nothing
Guard shared statecount++ and list.Add from concurrent continuations silently corrupt

Async does not make your data thread-safe

This is the trap people fall into after they have understood await. Continuations can resume on different threads, and Task.WhenAll means several are in flight at once:

var results = new List<int>();                   // NOT thread-safe
await Task.WhenAll(ids.Select(async id =>
{
    int value = await LoadAsync(id);
    results.Add(value);                          // torn state, lost items, or an exception
}));

Three correct options, in order of preference:

int[] ordered = await Task.WhenAll(ids.Select(LoadAsync));    // let WhenAll collect for you
var bag = new ConcurrentBag<int>();                            // a concurrent collection
Interlocked.Add(ref total, value);                             // atomic for simple counters

And note you cannot await inside a lock — it is a compile error, because a monitor is owned by a thread and your continuation may resume on a different one. When you need mutual exclusion across an await, use SemaphoreSlim(1) and await gate.WaitAsync().

The built-in throttle

Hand-rolling ForEachAsync is instructive, but .NET 6 ships it:

await Parallel.ForEachAsync(ids, new ParallelOptions { MaxDegreeOfParallelism = 4 },
    async (id, token) => await ProcessAsync(id, token));

It does not collect results, so keep the semaphore version when you need the return values in order.

Two ways to time out, one of them wrong

// Good: the operation itself is told to stop.
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(2));
await LoadAsync(cts.Token);

// Bad: you stop waiting, but the work keeps running unobserved.
Task<int> work = LoadAsync(CancellationToken.None);
if (await Task.WhenAny(work, Task.Delay(2000)) != work) throw new TimeoutException();

The second version leaves an orphan. .NET 8 added await work.WaitAsync(TimeSpan.FromSeconds(2)) for the cases where the operation genuinely cannot be cancelled.

Distinguishing your timeout from the caller's cancellation is worth the extra line:

catch (OperationCanceledException) when (!callerToken.IsCancellationRequested)
{
    // our deadline fired: this is a timeout, and retrying may be reasonable
}

Retry only what is worth retrying

Retrying a 503 or a socket timeout is sensible. Retrying a 400, a validation failure or an ArgumentException just wastes time and multiplies the log noise. Filter with an exception filter, add jitter so a thousand clients do not retry in lockstep, and cap the total attempts:

catch (HttpRequestException ex) when (attempt < max && IsTransient(ex))

In production, prefer a library — Polly gives you retry, circuit breaker, bulkhead and timeout as composable policies, and a circuit breaker is what stops your retries from becoming the outage.

Fire and forget, done properly

SendEmailAsync();                        // CS4014: nobody observes this, ever

_ = Task.Run(async () =>                 // at minimum: swallow deliberately, log always
{
    try { await SendEmailAsync(); }
    catch (Exception ex) { Log(ex); }
});

Better still, do not fire and forget. Put the work on a queue and let a background service own it — IHostedService / BackgroundService in ASP.NET Core — so it survives a shutdown and shows up in your telemetry.

ValueTask has rules

ValueTask<T> avoids an allocation when a method usually completes synchronously — a cache hit, a buffered read. The price is a stricter contract: await it exactly once, never in parallel, never store it. If you want to use the result twice, call .AsTask() first. Use it in hot library paths after measuring; use Task<T> everywhere else.

Sync implementations of async contracts

When an interface demands a Task and your implementation has nothing to await, do not write async with no await (CS1998):

public Task<int> GetAsync() => Task.FromResult(42);
public Task SaveAsync() => Task.CompletedTask;
public Task FailAsync() => Task.FromException(new NotSupportedException());

Async disposal

Anything holding a stream, a connection or a channel should clean up asynchronously:

await using var connection = new SqlConnection(cs);        // calls DisposeAsync

Implement IAsyncDisposable when Dispose would otherwise block on network work.

Progress, without polling

static async Task CopyAsync(int total, IProgress<int> progress)
{
    for (int i = 1; i <= total; i++) { await Task.Delay(10); progress.Report(i * 100 / total); }
}

await CopyAsync(10, new Progress<int>(p => Console.WriteLine($"{p}%")));

Progress<T> marshals the callback back to the captured context, so updating a UI control from it is safe.

Turn the compiler up

CS1998 (async without await) and CS4014 (unawaited task) are the two warnings that catch real async bugs. Set <TreatWarningsAsErrors>true</TreatWarningsAsErrors> and they stop being suggestions.


Real World Example: A Webhook Dispatcher That Behaves Itself

Every rule on the card shows up in one place: sending outbound HTTP to endpoints you do not control. They are slow, they lie about being up, and if you retry them carelessly you become the outage.

using System;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

record Webhook(string Target, int LatencyMs, int FailFirst);

class Dispatcher
{
    private readonly SemaphoreSlim gate;
    private readonly TimeSpan perCallLimit;
    private int delivered;
    private int attemptsUsed;

    public Dispatcher(int concurrency, TimeSpan perCallLimit)
    {
        gate = new SemaphoreSlim(concurrency);
        this.perCallLimit = perCallLimit;
    }

    public int Delivered => delivered;
    public int AttemptsUsed => attemptsUsed;

    private async Task PostAsync(Webhook hook, int attempt, CancellationToken token)
    {
        Interlocked.Increment(ref attemptsUsed);          // shared counter, touched atomically
        await Task.Delay(hook.LatencyMs, token);          // stands in for HttpClient.PostAsync
        if (attempt <= hook.FailFirst)
            throw new HttpRequestException($"HTTP 503 from {hook.Target}");
    }

    public async Task<string> SendAsync(Webhook hook, CancellationToken token)
    {
        await gate.WaitAsync(token);                     // throttle: N in flight, no more
        try
        {
            for (int attempt = 1; attempt <= 3; attempt++)
            {
                using var perCall = CancellationTokenSource.CreateLinkedTokenSource(token);
                perCall.CancelAfter(perCallLimit);       // a deadline per attempt

                try
                {
                    await PostAsync(hook, attempt, perCall.Token);
                    Interlocked.Increment(ref delivered);
                    return $"ok       {hook.Target,-22} attempt {attempt}";
                }
                catch (OperationCanceledException) when (!token.IsCancellationRequested)
                {
                    if (attempt == 3) return $"timeout  {hook.Target,-22} after {attempt} attempts";
                }
                catch (HttpRequestException ex)
                {
                    if (attempt == 3) return $"failed   {hook.Target,-22} {ex.Message}";
                }

                await Task.Delay(30 * attempt, token);   // linear backoff between attempts
            }

            return $"failed   {hook.Target,-22} unreachable";
        }
        finally
        {
            gate.Release();                              // in finally, or the gate leaks
        }
    }
}

class Program
{
    static async Task Main()
    {
        Webhook[] hooks =
        {
            new("https://a.example/hook",  20, 0),       // clean first time
            new("https://b.example/hook",  20, 1),       // one transient failure
            new("https://c.example/hook", 500, 0),       // slower than the 150ms deadline
            new("https://d.example/hook",  20, 5)        // permanently broken
        };

        var dispatcher = new Dispatcher(concurrency: 2, perCallLimit: TimeSpan.FromMilliseconds(150));
        using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));   // overall budget

        string[] lines = await Task.WhenAll(hooks.Select(h => dispatcher.SendAsync(h, cts.Token)));

        foreach (string line in lines) Console.WriteLine(line);
        Console.WriteLine($"delivered {dispatcher.Delivered}/{hooks.Length} using {dispatcher.AttemptsUsed} attempts");
    }
}

Output:

ok       https://a.example/hook attempt 1
ok       https://b.example/hook attempt 2
timeout  https://c.example/hook after 3 attempts
failed   https://d.example/hook HTTP 503 from https://d.example/hook
delivered 2/4 using 9 attempts

Nine attempts for four hooks: one each for a, two for b, three each for the two that were never going to work. Every rule is visible. The semaphore capped concurrency at two. Each attempt had its own 150ms deadline, linked to a 10-second overall budget so the caller can still cancel everything. The exception filter told a timeout apart from a cancellation. Backoff grew with each attempt. Both counters used Interlocked because four tasks share them. And the release sits in finally, which is the difference between a dispatcher that recovers from failure and one that quietly stops working after the fourth error.

What is deliberately missing is a circuit breaker: after d fails a few dozen times you should stop calling it for a while rather than retrying forever. That is where reaching for Polly beats extending this class.


Common Mistakes

  1. Blocking with .Result, .Wait() or GetAwaiter().GetResult() to bridge sync and async. Make the caller async instead; every workaround is a deadlock waiting for the right host.
  2. Unbounded fan-out. Task.WhenAll(items.Select(SendAsync)) over 10,000 items opens 10,000 operations at once. Throttle it.
  3. Retrying without backoff, jitter or a cap, and retrying errors that will never succeed. That is how a client turns a blip into an outage.
  4. Mutating a List<T>, Dictionary<K,V> or int from concurrent continuations. Use WhenAll's results, a concurrent collection, or Interlocked.
  5. Thread.Sleep in an async method. It blocks a pool thread; await Task.Delay does not.
  6. Releasing a semaphore outside finally. One exception and a permit is gone forever.
  7. Fire and forget with no try/catch. The exception is unobserved, the log is silent, and the bug is unfindable.
  8. Awaiting a ValueTask<T> twice, or storing one in a field. The contract allows the underlying object to be recycled; the behaviour after a second await is undefined.

Best Practices

  • Async all the way up, tokens all the way down. Those two sentences prevent most async bugs you will ever hit.
  • Bound your concurrency explicitly with SemaphoreSlim or Parallel.ForEachAsync, and pick the number deliberately rather than letting the input size choose it.
  • Give every outbound call a deadline, and link per-call token sources to the caller's token so cancellation composes.
  • Retry transient failures only, with growing delays and jitter, a hard attempt cap, and a circuit breaker once the call matters.
  • Prefer Task.WhenAll's return value to shared mutable state. If you must share, use Interlocked or a Concurrent* collection — and remember await cannot appear inside lock.
  • Return Task.CompletedTask / Task.FromResult for synchronous implementations instead of an async method with no await.
  • Use await using and IAsyncDisposable for anything whose cleanup touches the network, and IProgress<T> to report progress instead of polling.
  • Turn CS1998 and CS4014 into errors. They are the compiler telling you about the two mistakes that hide best.

Practice Exercises

  1. Write static async Task<string[]> FetchAllAsync(string[] urls, int limit) that uses a SemaphoreSlim to allow only limit simulated fetches at once, each a Task.Delay. Track the peak number in flight with Interlocked and print it to prove the gate held — then remove the finally around Release, make one call throw, and describe what happens on the next run.
  2. Implement WithRetryAsync so it retries only HttpRequestException and TimeoutException, adds random jitter of 0–50ms to each delay, and gives up after four attempts by rethrowing. Prove it with a method that fails twice then succeeds, and a second that always throws ArgumentException — showing the second is not retried at all.
  3. Demonstrate the shared-state bug: run 200 concurrent tasks that each do total += 1 on a shared int and print the result, then repeat with Interlocked.Increment. Report both numbers and explain why only one of them is reliably 200.
  4. Extend the Dispatcher with a simple circuit breaker: after a target fails three times, record it in a ConcurrentDictionary<string,int> and short-circuit further sends to it with "open target" instead of calling out. Add a fifth hook pointing at the same broken target as d and show the breaker refusing it, then add a comment on why the dictionary must be a concurrent one.