Start With Plain await

For a service with modest traffic and a few awaited calls, write async methods, await each call and return Task. That's enough. The patterns below matter once the service is under real load, fans out over collections, or has callers who give up and leave.

Take a typical case, made up for illustration. A checkout API sailed through normal traffic and fell over at the start of a flash sale. CPU was low, memory was fine, and p99 went from about 120 ms to 9 seconds. A memory dump showed hundreds of threads parked in Task.Result, inside a helper someone had written to avoid making one method async.

That is thread-pool starvation, a common way async code hurts under load. The model is simple once it clicks: awaiting incomplete asynchronous work can suspend the method without blocking its thread, while synchronous waits keep a thread occupied. Below is how continuations run, how to fan out without flattening dependencies, how cancellation should flow, and the mistakes that cause deadlocks and crashes.

If latency climbs while CPU stays low
  • You sprinkle .ConfigureAwait(false) everywhere because someone said you should — but you can't articulate why
  • You've seen .Result or .Wait() deadlock production and don't fully trust async anymore
  • You fan out 1,000 HTTP calls with Task.WhenAll and the host falls over
  • You want to process 50 downloads as they finish instead of waiting for all of them
Reader contract
  • Outcome: Diagnose thread-pool starvation and choose cancellation, fan-out, and continuation patterns deliberately.
  • Environment: .NET 10 LTS application baseline, with APIs from .NET 8 and .NET 9 named where they first shipped, and clearly labelled .NET 11 preview material.
  • Code status: The C# blocks are partial snippets requiring surrounding types, dependency injection, logging, and tests.
  • Scope: Covers task-based application code—not UI dispatchers, custom schedulers, durable job infrastructure, or provider-specific billing.

What Actually Happens at an await

async doesn't create a thread. It restructures your method into a state machine that registers a continuation when it hits await. Whoever completes the awaited task triggers that continuation — often on a thread-pool thread, sometimes through a captured SynchronizationContext or non-default TaskScheduler. ASP.NET Core does not install its own synchronization context, which reduces the need for context-avoidance advice in ordinary application code without making that advice universally irrelevant.


sequenceDiagram
    participant C as Caller
    participant M as async Method
    participant IO as I/O (HTTP/DB)
    participant TP as ThreadPool

    C->>M: await DoAsync()
    M->>IO: start request (no thread blocked)
    Note over M,IO: ⏳ method suspends, thread freed
    IO-->>TP: completion event
    TP->>M: resume continuation on TP thread
    M-->>C: return result

Two things to internalize: (1) awaiting an incomplete asynchronous operation can suspend the method without blocking the calling thread. An already-completed awaitable can continue synchronously. (2) A blocked await (.Result, .Wait()) holds a thread doing nothing until the task completes, which is fine until it's not (deadlock with a captured context, thread-pool starvation under load).

✅

Check it: Search the request path for .Result and .Wait(). Each one holds a thread for as long as it waits.

Async Patterns That Hold Up Under Load

Step 1: ConfigureAwait — the modern story

// ASP.NET Core, console and worker apps normally have no SynchronizationContext, so
// .ConfigureAwait(false) usually changes nothing in application code. It matters again
// if something installs a custom SynchronizationContext or TaskScheduler.
public async Task<User> GetUserAsync(int id, CancellationToken ct)
{
    var user = await db.Users.FindAsync([id], ct);  // resumes on a TP thread either way
    return user;
}

// In LIBRARY code that may be called from a UI app — yes, use ConfigureAwait(false).
public async Task<string> ReadFileAsync(string path)
{
    using var reader = new StreamReader(path);
    return await reader.ReadToEndAsync().ConfigureAwait(false);
}

// .NET 8+ — ConfigureAwaitOptions enum gives finer control
await SomeTask.ConfigureAwait(ConfigureAwaitOptions.SuppressThrowing);
// ↑ Observes completion without propagating Faulted/Canceled. This does not make the work
//   durable, retry it, or coordinate application shutdown. Plain Task only: on Task<T>
//   this throws at runtime.

await CriticalTask.ConfigureAwait(
    ConfigureAwaitOptions.ContinueOnCapturedContext | ConfigureAwaitOptions.ForceYielding);
// ↑ Forces the await to yield even if the task already completed.

Ordinary ASP.NET Core code normally has no custom SynchronizationContext, so .ConfigureAwait(false) usually does not change application behaviour. A custom context or non-default TaskScheduler changes that analysis, which is why reusable libraries need separate guidance. SuppressThrowing is useful only when deliberately observing completion without propagating failure; it is not a background-work reliability mechanism. Owned workers or durable queues are the right boundary when work must survive request completion or shutdown.

Step 2: Fan-out with Task.WhenAll and Task.WhenEach

// Classic — wait for all, fail if any fail
public async Task<IReadOnlyList<string>> FetchAllAsync(IEnumerable<string> urls, CancellationToken ct)
{
    var tasks = urls.Select(u => http.GetStringAsync(u, ct));
    return await Task.WhenAll(tasks);
}

// .NET 9 — process results AS THEY COMPLETE instead of waiting for all
public async Task ProcessFastestFirstAsync(IEnumerable<string> urls, CancellationToken ct)
{
    var tasks = urls.Select(u => http.GetStringAsync(u, ct)).ToList();

    await foreach (Task<string> finished in Task.WhenEach(tasks).WithCancellation(ct))
    {
        try
        {
            var body = await finished; // unwrap; throws if this task failed
            await HandleAsync(body, ct);
        }
        catch (Exception ex)
        {
            logger.LogWarning(ex, "One URL failed; continuing");
        }
    }
}

Before .NET 9 you had to roll your own loop with Task.WhenAny and remove finished tasks from a list. Task.WhenEachreturns an IAsyncEnumerable<Task> — you just await foreach over completions in the order they happen. Use this whenever "I want to start showing results as they arrive" beats "I want them in input order".

Step 3: Bounded concurrency — Parallel.ForEachAsync

// WRONG — fires 10,000 simultaneous HTTP calls. Hits socket limits, server bans you,
// and your dependencies take the hit.
await Task.WhenAll(items.Select(i => http.GetStringAsync(i.Url, ct)));

// RIGHT — Parallel.ForEachAsync (.NET 6+) caps concurrency cleanly
var options = new ParallelOptions
{
    MaxDegreeOfParallelism = 16,
    CancellationToken = ct,
};

await Parallel.ForEachAsync(items, options, async (item, token) =>
{
    var body = await http.GetStringAsync(item.Url, token);
    await ProcessAsync(item, body, token);
});

Task.WhenAll has no built-in throttle. For anything user-controlled in size, use Parallel.ForEachAsync with a sane MaxDegreeOfParallelism, or a SemaphoreSlim(maxConcurrency). Outbound HTTP and DB connections are the most common cause of cascading failures from unbounded fan-out.

✅

Check it: Find every Task.WhenAll over a collection whose size a user controls. Each one needs a limit, chosen from what the downstream system can take.

Step 4: Cancellation hygiene

// Always accept and propagate CancellationToken — including in private helpers
public async Task<Order> CreateOrderAsync(OrderInput input, CancellationToken ct)
{
    var customer = await customers.FindAsync(input.CustomerId, ct);
    var items = await inventory.ReserveAsync(input.LineItems, ct);
    var order = new Order(customer, items);
    await orders.AddAsync(order, ct);
    return order;
}

// Combine timeouts with caller cancellation
public async Task<T> WithTimeoutAsync<T>(Func<CancellationToken, Task<T>> work,
                                         TimeSpan timeout,
                                         CancellationToken outer)
{
    using var cts = CancellationTokenSource.CreateLinkedTokenSource(outer);
    cts.CancelAfter(timeout);
    return await work(cts.Token);
}
✅

Check it: Start a slow request and close the connection. The database query behind it should stop.

How Async Code Fails in Production

1. async void outside event handlers. The caller can't catch or observe the exception. It surfaces on the thread pool or synchronization context, and unhandled it can crash the process. Always return Task or ValueTask. The single legitimate use is event handlers in UI/legacy frameworks.

2. .Result / .Wait() in app code. In any code that has a SynchronizationContext(older WinForms/WPF/classic ASP.NET), this is the textbook deadlock. In ASP.NET Core it doesn't deadlock but blocks a thread-pool thread, leading to starvation under load. Just await.

3. Forgetting to pass CancellationToken. A method that takes a CancellationToken but doesn't forward it to the calls inside is theatre. Audit with dotnet format analyzers --severity warn and the CA2016 rule.

4. Unbounded fan-out. Task.WhenAll(items.Select(...)) with a 10k-item list will exhaust connection pools. Use Parallel.ForEachAsync or a SemaphoreSlim. Production has limits; your code must too.

5. ValueTask misuse. A ValueTask can only be awaited once. Storing it in a field or awaiting twice is undefined behaviour. Use Task by default; reach for ValueTask only for hot paths where the synchronous-completion case dominates (e.g., cached lookups).

6. Mixing await and using. A using block scopes disposal to the synchronous extent. For types that implement IAsyncDisposable (DbContext, Stream), use await using so disposal itself runs asynchronously. HttpResponseMessage isn't one of them: it only implements IDisposable, and await using on it won't compile.

Rules I Follow

  • Stop adding .ConfigureAwait(false) in ASP.NET Core app code. Keep it in shared library code that may be called from UI apps.
  • Use the .NET 8 ConfigureAwaitOptions.SuppressThrowing only when observing a plain Task without propagating its failure is the intended policy. Use an owned worker or durable queue when completion matters.
  • Use Task.WhenEach (.NET 9) when you want to process results as they complete. Use Task.WhenAll when you need them all before continuing.
  • Bound your concurrency with Parallel.ForEachAsync or SemaphoreSlim. Unbounded Task.WhenAll is a failure waiting for traffic.
  • Accept and forward CancellationToken through every async path — including timeouts via CancellationTokenSource.CreateLinkedTokenSource.
  • Treat async void as banned outside event handlers. The caller can't catch its exceptions, and an unhandled one can crash the process.
  • Prefer await using over using for any IAsyncDisposable, such as DbContext or FileStream.

Cancellation, the Part Everyone Skips

Most async code I review handles the happy path well and ignores cancellation. Then a client disconnects, and your server keeps running an expensive query for a response nobody will read. In ASP.NET Core, the framework gives you a token through HttpContext.RequestAborted, or as a CancellationToken parameter on an endpoint. Pass it all the way down, to every database call, HTTP call and model call.

public async Task<Report> BuildAsync(int id, CancellationToken ct)
{
    using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
    timeout.CancelAfter(TimeSpan.FromSeconds(30));

    var rows = await _db.Reports.Where(r => r.Id == id).ToListAsync(timeout.Token);
    return await _llm.SummariseAsync(rows, timeout.Token);
}

For LLM calls this has a direct cost: cancelling can stop further generation, though how a partly finished request is billed depends on the provider.

What's coming in .NET 11

.NET 11 is due in November and includes runtime async as a preview feature, which you opt into with <Features>runtime-async=on</Features>. It moves the async state machine from the compiler into the runtime, for cleaner stack traces and lower overhead. It's a good reminder not to depend on compiler-generated implementation details.

Try It on Your Own System This Week

Three checks on a service you already run, about an hour in total:

  1. Turn on the CA2016 analyzer rule. It lists the calls where a token was available and not passed on.
  2. Search for async void. Outside event handlers, each one is an exception nobody can catch.
  3. Load test until p99 climbs, and watch the CPU. Latency that rises while CPU stays low points at blocked threads.

Completion Check

  • No request path uses .Result, .Wait(), or unbounded fan-out.
  • Cancellation flows from the caller through database, HTTP, and model operations and has an exercised cancellation test.
  • Concurrency limits reflect the downstream system's capacity rather than an arbitrary task count.
  • Failures are observed and owned; work that must complete after a request uses a hosted worker or durable queue.
  • Examples compile against the declared target framework, including disposal and Task<T> behaviour.