Async performance in .NET 10: ValueTask and pooled builders, eliding the async state machine safely, the real effect of ConfigureAwait in ASP.NET Core versus libraries, and bounding concurrent fan-out.
Async overhead is small (a state machine, a Task allocation and a continuation), so I only tune it on hot paths a profile points to.
ValueTask<T> removes the Task allocation when the method usually completes synchronously, such as a cache hit. Callers must await it exactly once.async/await and returning the inner Task saves a state machine for pure pass-through methods, but not when there's using, try or AsyncLocal state.ConfigureAwait(false) changes nothing in ASP.NET Core, which has no SynchronizationContext; it still matters in shared libraries.Parallel.ForEachAsync or SemaphoreSlim so a fan-out doesn't exhaust connection pools.The trade-off: these micro-optimisations add rules and risk, so the benchmark must justify them.
"I first put async cost in perspective. When an async method actually suspends, it allocates the state machine box, possibly a Task, and schedules a continuation; that's a few hundred bytes and well under a microsecond. Against a 5-millisecond database call it's noise, so I only tune async code when a profile shows it on a hot path, such as a cache read called millions of times or a stream parser.
On those paths I use a few tools.
ValueTask<T>is for methods that usually complete synchronously, like a memory cache hit: the result is returned inline with no allocation, and only the miss path allocates. Callers must await it once and never call.Resulton an incomplete one. I elideasyncand just return the Task for one-line pass-through wrappers, but never when there's ausing, atry/catchorAsyncLocalstate, because the disposal or exception happens at the wrong time.ConfigureAwait(false)is a library concern: ASP.NET Core has noSynchronizationContext, so in app code it changes nothing, while in a NuGet package it protects UI and legacy callers.The mistake I see is people obsessing over those details while doing
Task.WhenAllover 5,000 HTTP calls with no limit. That exhausts sockets and the downstream service. Bounding concurrency withParallel.ForEachAsyncand aMaxDegreeOfParallelism, and making sure nothing blocks a thread, is where async performance is really won."
| Cost | When it happens | Mitigation |
|---|---|---|
| State machine box | Method suspends at an await | Elide for pass-through; PoolingAsyncValueTaskMethodBuilder on extreme hot paths |
Task<T> allocation |
Every call (cached for some values like Task.CompletedTask, small ints, bools) |
ValueTask<T> when sync completion is common |
| Continuation scheduling | On resume | Usually negligible; avoid unnecessary awaits in loops |
| Blocked threads | .Result, .Wait(), sync I/O |
Async all the way |
| Unbounded fan-out | WhenAll over a huge list |
Parallel.ForEachAsync, SemaphoreSlim, Channels |
Task<T> |
ValueTask<T> |
|
|---|---|---|
| Allocation on sync completion | Yes (unless cached) | No |
| Await multiple times | Yes | No |
WhenAll, store in a field |
Yes | Convert with .AsTask() first |
| Default choice | Yes | Only when measured hot and often synchronous |
| Context | Effect of ConfigureAwait(false) |
|---|---|
| ASP.NET Core app code | None (no SynchronizationContext) |
| Library used by WPF/WinForms/MAUI/legacy ASP.NET | Avoids marshalling back and the classic deadlock |
ConfigureAwaitOptions (.NET 8+) |
SuppressThrowing, ForceYielding for specific needs |
A pricing API fanned out to a supplier for every line of a quote with Task.WhenAll; quotes with 800 lines opened 800 concurrent connections and drew 429s. Limiting to 16 concurrent calls with Parallel.ForEachAsync cut large-quote p95 from 9 s to 2.1 s with zero 429s. Separately, switching a hot cache lookup to ValueTask<T> cut 120 MB/s of allocations at 50,000 calls a second.
Checks whether the candidate understands where async overhead really comes from and focuses on the optimisations that matter in production.
Green flags
Red flags
An async method becomes a struct state machine plus a builder. If every await completes synchronously, the struct stays on the stack and the builder returns a completed task (cached for common values). The first time an await is incomplete, the state machine is boxed to the heap so it can resume later, and the builder creates the Task<T> the caller awaits.
call --> run to first await --(completed?)--> continue inline --> return cached/completed task
\--(pending)--> box state machine, register continuation,
return Task; resume later on ThreadPool
ValueTask<T> is a struct wrapping either a T (sync result), a Task<T> or an IValueTaskSource<T> (a reusable, poolable completion object). Sockets and PipeReader use IValueTaskSource so steady-state reads allocate nothing. Because the source may be reused after you consume it, awaiting twice or awaiting concurrently is undefined behaviour. [AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder<>))] (.NET 6+) pools the boxes for a method, trading memory held in pools for fewer allocations; measure before using it.
public Task<User?> GetAsync(int id, CancellationToken ct) => _repo.GetAsync(id, ct); // fine
This is safe when the method only forwards. It breaks when the method has a using (the resource is disposed before the task completes), a try/catch (exceptions surface outside it), or argument validation you expect to throw lazily.
await captures SynchronizationContext.Current (or a non-default TaskScheduler) and posts the continuation back to it. UI frameworks and classic ASP.NET have one; ASP.NET Core and console apps don't, so continuations run on the ThreadPool anyway. Libraries can't know their host, so they keep ConfigureAwait(false).
Each concurrent outbound call holds a socket or pooled connection, memory for buffers, and load on the downstream service. Parallel.ForEachAsync(items, new ParallelOptions { MaxDegreeOfParallelism = 16, CancellationToken = ct }, ...) runs at most 16 bodies at once. SemaphoreSlim(16) around WhenAll does the same with more control. For pipelines, a bounded Channel<T> adds backpressure.
Task.Run around async I/O in ASP.NET Core: adds a ThreadPool hop and gains nothing.async void: loses exceptions and can crash the process.Task<int> vs ValueTask<int> with [MemoryDiagnoser] at 100% and 50% hit rates.using and elide async; write a test that shows the object disposed too early.WhenAll vs Parallel.ForEachAsync (MaxDegreeOfParallelism 16); compare latency and dotnet-counters connection counts.A hot cache lookup using ValueTask<T>, a safe elided pass-through, and a bounded fan-out.
using System.Collections.Concurrent;
namespace Perf.Async;
public sealed record Price(string Sku, decimal Amount);
public interface IPriceSource
{
Task<Price> FetchAsync(string sku, CancellationToken ct);
}
public sealed class PriceCache(IPriceSource source)
{
private readonly ConcurrentDictionary<string, Price> _cache = new();
// Hit path: completes synchronously, no Task allocation.
// Miss path: falls through to a real async method.
public ValueTask<Price> GetAsync(string sku, CancellationToken ct) =>
_cache.TryGetValue(sku, out var price)
? ValueTask.FromResult(price)
: new ValueTask<Price>(LoadAsync(sku, ct));
private async Task<Price> LoadAsync(string sku, CancellationToken ct)
{
var price = await source.FetchAsync(sku, ct);
_cache[sku] = price;
return price;
}
// Safe to elide async: pure pass-through, no using/try/AsyncLocal.
public Task<Price> RefreshAsync(string sku, CancellationToken ct) => source.FetchAsync(sku, ct);
}
public sealed class QuoteService(PriceCache cache)
{
// Bounded fan-out: at most 16 concurrent lookups, so a 5,000-line quote
// can't open 5,000 connections to the supplier.
public async Task<IReadOnlyList<Price>> PriceQuoteAsync(IReadOnlyList<string> skus, CancellationToken ct)
{
var results = new Price[skus.Count];
await Parallel.ForEachAsync(
Enumerable.Range(0, skus.Count),
new ParallelOptions { MaxDegreeOfParallelism = 16, CancellationToken = ct },
async (i, token) => results[i] = await cache.GetAsync(skus[i], token));
return results;
}
}
ValueTask everywhere. Why it is wrong: It adds consumption rules with no measurable gain. Instead: Default to Task; use ValueTask where sync completion is common and the call is hot.ValueTask twice or calling .Result on it. Why it is wrong: The underlying source may be reused, giving wrong results or exceptions. Instead: Await once, or call .AsTask() if you need Task semantics.async in a method with using. Why it is wrong: The resource is disposed before the returned task finishes. Instead: Keep async/await whenever there's cleanup or exception handling.ConfigureAwait(false) everywhere in ASP.NET Core apps 'for speed'. Why it is wrong: There's no context to avoid; it's noise. Instead: Use it in libraries.Task.WhenAll over large inputs. Why it is wrong: Exhausts sockets, connection pools and downstream rate limits. Instead: Parallel.ForEachAsync with a limit, or SemaphoreSlim.Task.Run around I/O in a request. Why it is wrong: Wastes a ThreadPool thread and a hop. Instead: Call the async API directly.The senior view is that async is mainly a scalability tool (threads aren't held during I/O), not a latency tool; the performance problems that matter are blocking, unbounded concurrency and chatty I/O, not state machine allocations. Reserve ValueTask and pooled builders for library-style hot paths and prove them with BenchmarkDotNet and production alloc-rate.
| Technique | When it fits | Cost | When not to |
|---|---|---|---|
ValueTask<T> |
Hot, mostly synchronous completion | Consumption rules; harder APIs | Public APIs where callers will misuse it |
| Eliding async | One-line forwarding | Subtle bugs if cleanup added later | Any using, try or validation |
ConfigureAwait(false) |
Libraries | Noise in app code | ASP.NET Core application code |
| Bounded parallelism | Fan-out to I/O | Choosing and tuning a limit | Strictly sequential workflows |
ValueTask<T> is a struct that holds either a result, a Task<T> or an IValueTaskSource<T>. It avoids allocating a task when a method usually completes synchronously (cache hits, buffered reads) and lets libraries pool the async case. The cost is stricter rules: await it once, never await it concurrently, and never read .Result before it completes; call .AsTask() if you need any of that. Use Task by default and choose ValueTask for measured hot paths or when an interface already uses it, like Stream.ReadAsync(Memory<byte>) or IAsyncDisposable.DisposeAsync.
ConfigureAwait(false) tells an await not to resume on the captured SynchronizationContext or custom TaskScheduler; the continuation runs on a ThreadPool thread instead. Use it in general-purpose library code, which should not depend on or block the caller's context, to avoid deadlocks and save context switches. Do not use it in UI code that must touch controls after the await. In ASP.NET Core application code it is optional because there is no context. Since .NET 8, ConfigureAwait(ConfigureAwaitOptions) adds SuppressThrowing (await a Task without throwing) and ForceYielding (always continue asynchronously).
Parallel.ForEachAsync (.NET 6+) runs an async body for each item in a sequence (IEnumerable<T> or IAsyncEnumerable<T>) with a bounded number of concurrent operations, set by ParallelOptions.MaxDegreeOfParallelism (default: processor count). The body receives a CancellationToken that is cancelled if any iteration throws, so it stops early on failure. It is the simplest way to say "process these 10,000 items, at most 20 at a time". Compared with Task.WhenAll it limits concurrency; compared with SemaphoreSlim it needs less code. It does not return results, so write to a concurrent collection or a preallocated array.
How to tell it (STAR)
**S:** At [company] our quote API priced each line by calling a supplier, and large enterprise quotes of [800] lines were taking about [9 seconds] and triggering 429s. **T:** I owned fixing it before a key customer's renewal. **A:** I traced one slow request in Application Insights and saw [800] parallel calls from an unbounded Task.WhenAll. I reproduced it with k6, capped concurrency at 16 with Parallel.ForEachAsync, added retry honouring Retry-After, and later worked with the supplier on a batch endpoint. **R:** Large-quote p95 fell to [2.1 seconds], 429s went to zero, and the batch endpoint later cut supplier calls by [90%].
Last updated 23 Nov 2026.