Skip to content

Lesson 4 of 9 · 28m

Async All the Way Down, and the Cost of Getting It Wrong

Understand synchronization contexts, cancellation, blocking calls, and concurrency limits so async code improves scalability instead of hiding failure.

A service can survive terrible SQL longer than it can survive one innocent .Result in the wrong place. The blocking call looks harmless in review. Under load it pins threads, causes thread-pool injection delays, and turns a modest traffic spike into a staircase of timeouts. Async in .NET is not about making one operation faster. It is about not occupying scarce threads while work waits elsewhere.

Async is contagious for a reason

When the leaf operation is asynchronous, let the signature flow upward:

public static async Task<Results<Ok<InvoiceDto>, NotFound>> GetInvoice(
    Guid id,
    InvoiceRepository repository,
    CancellationToken ct)
{
    var invoice = await repository.FindAsync(id, ct);
    return invoice is null ? TypedResults.NotFound() : TypedResults.Ok(invoice);
}

Do not convert it back to synchronous at the edge with .Result, .Wait(), or GetAwaiter().GetResult(). Those calls block the current thread and can deadlock in synchronization-context environments. Even where modern ASP.NET Core avoids the classic deadlock, blocking still destroys scalability.

ASP.NET Core does not have the old SynchronizationContext

The old ASP.NET deadlock story came from captures on a single-threaded synchronization context. ASP.NET Core removed that trap, which causes some engineers to declare blocking safe. It is not. The thread is still occupied while waiting, and thread-pool starvation remains real. 'It no longer deadlocks' is not the same as 'it scales.'

Cancellation is part of the API contract

Accept CancellationToken at the edge and pass it through database calls, HTTP calls, queue operations, and streams:

public async Task<Invoice?> FindAsync(Guid id, CancellationToken ct)
{
    return await _db.Invoices
        .AsNoTracking()
        .FirstOrDefaultAsync(x => x.Id == id, ct);
}

If a client disconnects or a gateway times out, continuing the work is wasted capacity. In background jobs, cooperative cancellation also enables clean rolling deploys. Throwing OperationCanceledException during shutdown is normal; treat it differently from a failure in health and logging.

Parallelism is a resource budget

Task.WhenAll is not a license to launch unbounded work:

var results = new List<Result>();
foreach (var item in items)
{
    results.Add(await ProcessAsync(item, ct));
}

Sequential code is correct but may be too slow. Naive fan-out can be worse:

// Dangerous when items is large or ProcessAsync calls downstream services.
var tasks = items.Select(item => ProcessAsync(item, ct));
var results = await Task.WhenAll(tasks);

Use bounded parallelism. Parallel.ForEachAsync gives a clear budget:

await Parallel.ForEachAsync(items,
    new ParallelOptions { MaxDegreeOfParallelism = 4, CancellationToken = ct },
    async (item, token) => await ProcessAsync(item, token));

Choose the number based on downstream capacity, not wishful thinking.

Timer callbacks and fire-and-forget need supervision

Task.Run inside ASP.NET Core rarely does what people hope. It still uses thread-pool threads, still observes no request lifetime guarantee, and still dies during shutdown. For real background work use BackgroundService, a queue, or a worker process. If you intentionally fire and forget, capture exceptions and protect shutdown semantics; otherwise the service silently loses work.

Field notes

  • async void is for event handlers, not services. Exceptions escape normal task error handling and can terminate the process.
  • Do not use ConfigureAwait(false) as a cargo-cult performance ritual in application code; modern ASP.NET Core has no context to avoid capturing.
  • Cancellation is not guaranteed to stop database work instantly. It is cooperative and depends on provider behavior.
  • Measure thread-pool starvation with metrics, not vibes. Latency spikes with low CPU often mean threads are blocked or work is queued.

Was this lesson helpful?

Sign in to rate