
Task vs ValueTask: Why the Cheaper-Looking One Is Not the Default
- كاتب موثّق
- .NET 10
محتويات المقال
Task<T> to ValueTask<T>, with the description "ValueTask is the allocation-free Task." The load test after the merge shows the same allocation rate and the same latency as before. Nearly every one of those methods queries the database, so each call completes asynchronously and allocates just as it did. Meanwhile, the change quietly broke a rule in a helper that awaits the same lookup twice, once for the total and once for the log line. It passes every test today, and the docs say its behavior is undefined.
The common misconception
ValueTask<T> is a lighter Task<T>. A Task is a class allocated on the heap; a ValueTask is a struct, so returning it everywhere removes allocations and makes async code faster for free.
ValueTask precisely to cut allocations, and hot APIs in the base libraries, such as stream and socket reads, return it. Benchmarks of those APIs show real savings. And the name, with "Value" on the front, sounds like the version of the same thing.
What actually happens
Where a Task's cost comes from
await resumes through it. For an async Task<T> method, that object is the task itself, combined with the method's . When the method finishes without ever waiting, the runtime still needs a Task<T> holding the result. It reuses cached tasks for a few results, such as true and false, but any other value needs a new object.
What ValueTask saves, and when
ValueTask<T> is a struct that holds one of three things: the result itself, a Task<T>, or an IValueTaskSource<T>. If the result is ready when the method returns, it goes straight into the struct and nothing is allocated. If the method has to wait, the default async machinery allocates its in-flight object just as it would for a Task. The only ways around that allocation are sources: Socket keeps one reusable object for receives and one for sends, and since .NET 6 the PoolingAsyncValueTaskMethodBuilder lets an async method reuse its objects across calls. So a method that queries the database on every call saves nothing by returning ValueTask<T>.
What ValueTask costs
Task<T> is a single reference, so returning one copies more data, and every async method that awaits it gets a larger state machine. And because the object behind it may be pooled, the docs list operations you must never perform on a ValueTask: awaiting it more than once, calling AsTask more than once, reading .Result before it has completed, or mixing those techniques. Awaiting it from two callers at once breaks the same rule. If you do any of these, the results are undefined.
Why the misuse passes your tests
async ValueTask<T> method that has to wait is backed by an ordinary Task today, and a Task doesn't mind being awaited twice. So the helper from the pull request works. Back the same method with a pooled source, and after the first await its object returns to the pool, where the next call can take it over. A second await then reads an object that no longer belongs to your operation.
The double await, made visible
using System.Runtime.CompilerServices;ValueTask<decimal> price = GetPriceAsync("SKU-1");decimal total = await price;decimal logged = await price; // undefined; here: InvalidOperationException[AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder<>))]static async ValueTask<decimal> GetPriceAsync(string sku){ await Task.Delay(10); // stands in for a database call return 9.99m;}using System.Runtime.CompilerServices;decimal total = await GetPriceAsync("SKU-1"); // await it once, directlyTask<decimal> shared = GetPriceAsync("SKU-1").AsTask(); // need it twice?decimal logged = await shared; // a Task can be awaited any number of times[AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder<>))]static async ValueTask<decimal> GetPriceAsync(string sku){ await Task.Delay(10); // stands in for a database call return 9.99m;}await in the first tab throws "InvalidOperationException: Operation is not valid due to the current state of the object." Two callers awaiting the same pooled ValueTask at once can be worse: the second registration throws inside the async machinery, and in a .NET 10 test that exception went unhandled on a thread pool thread and terminated the process. The second tab follows the docs: await each ValueTask once, and if you need more, call AsTask() once and use only the Task from then on.
Where ValueTask pays off
Task:
using System.Collections.Concurrent;public sealed class PriceCache(IPriceStore store){ private readonly ConcurrentDictionary<string, decimal> _prices = new(); public ValueTask<decimal> GetAsync(string sku) => _prices.TryGetValue(sku, out var price) ? ValueTask.FromResult(price) // hit: nothing allocated : new ValueTask<decimal>(LoadAsync(sku)); // miss: wraps a Task private async Task<decimal> LoadAsync(string sku) { var price = await store.LoadPriceAsync(sku); _prices[sku] = price; return price; }}Task<decimal>, every hit would allocate a new task, because a price isn't one of the few cached results. If most calls are hits and the method runs thousands of times per second, that's worth measuring.
Task vs ValueTask
Task<T> | ValueTask<T> | |
|---|---|---|
WhenAll or WhenAny | AsTask(), which allocates |
How to apply it in your project
Keep Task as the default Return TaskandTask<T>from new async methods, especially public ones, since changing a public return type later breaks callers.Switch only with evidence Before moving a method to ValueTask<T>, profile allocations on that path and confirm that most calls complete synchronously, as cache hits or buffered reads do.Consume every ValueTask once Await a ValueTaskdirectly where you call the method. Don't store it, return it twice or await it from two places; callAsTask()once if you need aTask.Make CA2012 a warning Add dotnet_diagnostic.CA2012.severity = warningto.editorconfig, so stored, ignored or double-awaitedValueTaskvalues show up in every build.
Key takeaways
ValueTask<T>saves an allocation only when the result is ready on return, or when a pooled source backs it.When a method really waits, a default async ValueTask<T>allocates like aTask<T>, and the struct is larger to copy and store.A ValueTaskmay be awaited once; double, concurrent or early consumption is undefined and can break with pooled sources.Return Taskby default, and useValueTask<T>for hot paths where measurements show mostly synchronous completion.
التعليقات (0)