الانتقال إلى المحتوى
.NETPerformance· 7 دقائق للقراءة

Task vs ValueTask: Why the Cheaper-Looking One Is Not the Default

ValueTask saves an allocation only when the result is already there, and it asks a lot of its callers in return. When it pays off, and when it bites.

ReadIn

مقال كل يوم يفرق معاك

22 نوفمبر 2026
  • كاتب موثّق
  • .NET 10
محتويات المقال

A pull request changes every async method in an API's data layer from 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

The belief: 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.

There's real substance behind it. The .NET team introduced 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 the name hides is that the saving depends on how the method completes, and that the struct comes with rules its callers must follow.

What actually happens

Where a Task's cost comes from

When an async method has to wait, something on the heap must represent the operation in flight: the caller holds it, and the code after the 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

A 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

The struct has several fields, while a 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

A plain 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

Both tabs call the same method, marked with the pooling builder so that the misuse shows up. Only the way the result is consumed changes:

C# Program.cs
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;}

On .NET 10, the second 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

The textbook case is a hot method that usually has its answer ready, like a cache in front of a slower store. A hit returns the value inside the struct; only a miss pays for a Task:

C# PriceCache.cs
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;    }}

With 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

QuestionTask<T>ValueTask<T>
Result ready when the method returnsAllocates, except a few cached resultsAllocates nothing
Method really waitsAllocates its in-flight objectAllocates the same, unless a pooled source backs it
Size returned and stored by callersOne referenceSeveral fields
Await twice or from two callersFineUndefined
Pass to WhenAll or WhenAnyDirectlyOnly after AsTask(), which allocates

How to apply it in your project

  1. Keep Task as the defaultReturn Task and Task<T> from new async methods, especially public ones, since changing a public return type later breaks callers.
  2. Switch only with evidenceBefore 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.
  3. Consume every ValueTask onceAwait a ValueTask directly where you call the method. Don't store it, return it twice or await it from two places; call AsTask() once if you need a Task.
  4. Make CA2012 a warningAdd dotnet_diagnostic.CA2012.severity = warning to .editorconfig, so stored, ignored or double-awaited ValueTask values 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 a Task<T>, and the struct is larger to copy and store.
  • A ValueTask may be awaited once; double, concurrent or early consumption is undefined and can break with pooled sources.
  • Return Task by default, and use ValueTask<T> for hot paths where measurements show mostly synchronous completion.

📚 المصادر

  1. Understanding the Whys, Whats, and Whens of ValueTask — Stephen Toub, .NET Blog
  2. ValueTask<TResult> Struct: Remarks — Microsoft Learn
  3. CA2012: Use ValueTasks correctly — Microsoft Learn
  4. Performance Improvements in .NET 6: Async (PoolingAsyncValueTaskMethodBuilder) — Stephen Toub, .NET Blog

التعليقات (0)