skip to content

When should a C# method return ValueTask<TResult> instead of Task<TResult>, and why does Task<TResult> remain the default choice?

level: middleimportance: must knowfreq 55%

answer

  1. where the allocation happens
  2. usually completes synchronously
  3. cached Task results already exist
  4. measure first, then pay the restrictions

basics

~20 s

Return ValueTask<TResult> from a hot method that usually completes synchronously, so the result travels inline without a Task allocation. Otherwise keep Task<TResult>: it has no consumption rules, and a plain async ValueTask method saves nothing when it really goes asynchronous.

solid answer

~40 s

A `Task<TResult>` is a heap object, so a method called in a tight loop that usually already has its answer, such as a reader whose `ReadAsync` mostly returns bytes already in its buffer, pays an allocation per call for nothing. Returning `ValueTask<TResult>` lets that synchronous path carry the result inline in a struct. It buys nothing elsewhere: an ordinary `async ValueTask<TResult>` method that really suspends still allocates a task-backed object, and the runtime already returns cached tasks for `bool` results, `int` results from -1 to 8, `null` and some `default` values. Meanwhile every caller inherits the rules: await once, never concurrently, no `WhenAll` without `AsTask()`. Microsoft's TAP guidance says to use it only when measurements show allocation pressure and consumers can handle the extra constraints, which is why `Task<TResult>` stays the default.

code

csharp · 26 lines
csharp
using System.Threading.Tasks;

var reader = new BufferedReader();
for (int i = 0; i < 3; i++)
{
    ValueTask<int> pending = reader.ReadAsync();
    Console.WriteLine($"call {i}: completed synchronously = {pending.IsCompleted}");
    Console.WriteLine($"call {i}: value = {await pending}");
}

class BufferedReader
{
    private readonly Queue<int> _buffer = new([10, 20]);

    // Fast path: no Task<int> is allocated when a buffered value is ready.
    public ValueTask<int> ReadAsync() =>
        _buffer.TryDequeue(out int value)
            ? new ValueTask<int>(value)
            : new ValueTask<int>(FillAndReadAsync());

    private async Task<int> FillAndReadAsync()
    {
        await Task.Delay(10);        // stands in for network I/O
        return 30;
    }
}

go deeper

for a junior

Remember the rule of thumb: Task<TResult> by default, ValueTask<TResult> only for hot methods that usually already have their answer.

for a middle

Explain where the Task allocation comes from, why the struct avoids it only on the synchronous path, and which results Task.FromResult already caches.

for a senior

Show you would demand allocation data before the change, use a non-async fast path, and weigh the consumption rules imposed on every caller.

for a principal

Treat the return type as part of a public contract: ValueTask trades caller freedom for allocation savings, and reversing the choice later breaks every consumer.

## The allocation ValueTask<TResult> removes `Task<TResult>` is a **class**. When an `async Task<TResult>` method finishes without ever suspending, the method builder still has to hand the caller a task object, and for most result values that means a new heap allocation. One allocation is cheap; one per call on a path that runs millions of times per second is **allocation pressure** that shows up as garbage-collection work. `ValueTask<TResult>` is a **readonly struct**. On that synchronous path it simply carries the result, so no object is created. ## The worked case: a buffered network reader A reader that fills an internal buffer from the network in large chunks answers most `ReadAsync` calls from memory. Only when the buffer runs dry does it actually wait on I/O. That shape, **usually synchronous, occasionally asynchronous, called very often**, is the one `ValueTask<TResult>` was designed for. The example below returns the buffered value inline and wraps a `Task<int>` only on the slow path. ## What it does not save Three facts narrow the benefit: - **The asynchronous path still allocates.** An ordinary `async ValueTask<TResult>` method that really awaits something incomplete is driven by `AsyncValueTaskMethodBuilder<TResult>`, which boxes the state machine into a task-derived object; the `ValueTask` then just wraps that task. Pooling those boxes needs an opt-in builder, `PoolingAsyncValueTaskMethodBuilder<TResult>`, applied with `[AsyncMethodBuilder]`, which is covered with the compiler state machine. - **Some `Task<TResult>` results are already free.** When an `async Task<TResult>` method completes synchronously, its builder calls `Task.FromResult`, which returns cached tasks for the cases below. - **The struct is bigger than a reference.** A `ValueTask<TResult>` carries an object reference, the `TResult`, a `short` token and a flag, and it is copied at every hand-off. | Synchronous result | Cached `Task<TResult>` returned? | |---|---| | `true` or `false` | yes, both values | | `int` from -1 to 8 | yes | | `null`, or `default` of a small struct with no references | yes | | any other value | no, a new task | So an `async Task<bool>` method that completes synchronously already allocates no task, and switching it to `ValueTask<bool>` gains nothing on that path. ## What it costs every caller Choosing `ValueTask<TResult>` moves cost from the method to its callers: 1. They must await the result **once**, and never from two places concurrently. 2. They must not read `.Result` before it has completed. 3. They need `AsTask()` before using `Task.WhenAll`, `Task.WhenAny`, or caching the operation. 4. Changing an existing public method between the two return types later is a **breaking change**. ## A decision checklist 1. Start with `Task<TResult>`, or `Task` when there is no result. 2. Profile: is this method's task allocation actually visible in allocation data? 3. Does the method complete synchronously on most calls, with results the task cache does not already cover? 4. Will every caller simply `await` it? If many store or combine the result, the restrictions will bite. 5. Only if all of these hold, return `ValueTask<TResult>`. Microsoft's guidance on the Task-based Asynchronous Pattern says the same in one line: use `ValueTask` or `ValueTask<TResult>` "only when measurements show allocation pressure and when consumers can handle the extra usage constraints". (How to take those measurements belongs to the material on .NET performance tooling.) ## Signs the choice went the wrong way - Profiling shows the method **mostly completes asynchronously**, so the struct is just a wrapper around a task that is allocated anyway. - Callers keep calling `AsTask()` to use `Task.WhenAll` or to cache results, which recreates the allocation and adds a conversion. - Bugs appear where a value is awaited twice or read with `.Result` early, the consumption rules the change introduced. - The result type is `bool`, or a small set of `int` values, which the task cache already serves for free. Any of these suggests going back to `Task<TResult>`, or never leaving it. ## The cheaper alternative: a cached Task When the synchronous results come from a small, fixed set, you can keep `Task<TResult>` and cache completed tasks yourself, for example one `static readonly Task<string>` per known value, or return `Task.CompletedTask`, which is a cached instance, from a non-generic method. That removes the allocation without imposing any rules on callers, and it is often the better fix.

  • Does an async ValueTask<TResult> method that awaits real I/O avoid allocating?
    Not by default. When it suspends, `AsyncValueTaskMethodBuilder<TResult>` boxes the state machine into a task-derived object and the `ValueTask<TResult>` wraps it, so the cost matches `Task<TResult>`. Opting a method into `PoolingAsyncValueTaskMethodBuilder<TResult>` with `[AsyncMethodBuilder]` reuses pooled boxes instead, at the price of pool management; the builder mechanics belong to the compiler state machine material.
  • Why does switching an async Task<bool> method to ValueTask<bool> often achieve nothing?
    When an `async Task<TResult>` method completes synchronously, its builder calls `Task.FromResult`, and `Task.FromResult` returns one of two cached tasks for `true` and `false`. The synchronous path therefore already allocates no task; only an asynchronous completion allocates, and the default `ValueTask` builder allocates there too.
  • What is the usual pattern for a fast path without making the whole method async?
    Write a non-async method that checks for the ready case and returns `new ValueTask<TResult>(value)`, and otherwise returns `new ValueTask<TResult>(SlowPathAsync())` where the slow path is an ordinary `async Task<TResult>` method. The synchronous path then runs no state machine at all.

  • ValueTask makes every async method faster, so return it everywhere
  • A plain async ValueTask method never allocates, even when it awaits real I/O
  • Task.FromResult always allocates a new Task object
  • Switching a public method from Task to ValueTask is non-breaking because both are awaitable
  • ValueTask is worth it for any method that returns a value type