skip to content

When should a C# interface or virtual method that other teams implement return ValueTask<int> rather than Task<int>, as Stream.ReadAsync(Memory<byte>) does?

level: seniorimportance: nice to knowfreq 25%

answer

  1. you cannot see every implementation
  2. some complete synchronously, some pool
  3. the BCL added overloads, not changes
  4. a signature is hard to change

basics

~20 s

Use ValueTask<int> in an interface or virtual signature when many implementations will complete synchronously or want to pool operations, as buffered streams do. The choice binds every implementer and caller, and changing it later is a breaking change.

solid answer

~40 s

A concrete method can be profiled; an interface method cannot, because you do not know its implementations yet. `ValueTask<int>` keeps every option open for them: return the result inline when data is buffered, wrap a `Task<int>` from an ordinary `async` method, or back the value with a pooled `IValueTaskSource<int>`. That is why `Stream.ReadAsync(Memory<byte>, CancellationToken)` returns `ValueTask<int>`, and why the compiler-generated enumerator behind an async iterator implements `IValueTaskSource<bool>` so `MoveNextAsync()` need not allocate per element. The price is paid by callers, who must follow the await-once rules, and by you: switching an existing member between `Task<int>` and `ValueTask<int>` breaks compiled callers and code that stores or combines the result. Choose it for hot, high-volume abstractions; keep `Task<int>` for coarse operations.

code

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

IByteSource[] sources = [new MemorySource([1, 2, 3]), new NetworkSource()];
foreach (IByteSource source in sources)
{
    var buffer = new byte[4];
    int read = await source.ReadAsync(buffer);
    Console.WriteLine($"{source.GetType().Name}: {read} bytes");
}

// The signature other teams implement: ValueTask<int> leaves each implementation free.
interface IByteSource
{
    ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default);
}

// Always synchronous: the result travels inline in the ValueTask<int>, no Task allocated.
sealed class MemorySource(byte[] data) : IByteSource
{
    public ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
    {
        int count = Math.Min(data.Length, buffer.Length);
        data.AsSpan(0, count).CopyTo(buffer.Span);
        return new ValueTask<int>(count);
    }
}

// Really asynchronous: an ordinary async method that returns ValueTask<int>.
sealed class NetworkSource : IByteSource
{
    public async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
    {
        await Task.Delay(10, cancellationToken);   // stands in for a socket read
        buffer.Span[0] = 42;
        return 1;
    }
}

go deeper

for a junior

Recall that some BCL abstractions, such as Stream.ReadAsync over Memory<byte>, return ValueTask<int>, and that implementers can still write a normal async method.

for a middle

Explain the three ways an implementation can satisfy a ValueTask<int> signature and why an interface author cannot profile in advance.

for a senior

Justify the choice for a high-volume abstraction, explain the IAsyncEnumerator precedent, and know that changing the return type later breaks binaries and source.

for a principal

Weigh implementer freedom against caller discipline across teams, and prefer adding members over changing them when a contract must evolve.

## Why interfaces are the strongest case for ValueTask For a concrete method, the advice is simple: start with `Task<TResult>` and switch only when profiling shows the task allocation matters. An **interface** or **virtual** method breaks that loop. The author of the abstraction cannot profile implementations that do not exist yet, and once the signature ships, every implementer is stuck with its return type. `ValueTask<TResult>` is the more permissive return type **for implementers**. Whatever an implementation does internally, it can express it: - **Synchronous answer**: `return new ValueTask<int>(count);` with no task allocated. - **Ordinary async work**: write `async ValueTask<int> ReadAsync(...)`, or return `new ValueTask<int>(someTask)`. - **Pooled operations**: return `new ValueTask<int>(source, token)` from a reusable `IValueTaskSource<int>`, usually built on `ManualResetValueTaskSourceCore<int>`. A `Task<int>` signature allows only the second, plus caching completed tasks for a few known results. ## Precedents in the base class library | Member | Return type | Why | |---|---|---| | `Stream.ReadAsync(byte[], int, int, CancellationToken)` | `Task<int>` | the original overload, kept as it was | | `Stream.ReadAsync(Memory<byte>, CancellationToken)` | `ValueTask<int>` | buffered streams often answer synchronously | | `Stream.WriteAsync(ReadOnlyMemory<byte>, CancellationToken)` | `ValueTask` | buffered writes often complete synchronously | | `IAsyncEnumerator<T>.MoveNextAsync()` | `ValueTask<bool>` | called once per element | Two lessons stand out. First, the library **added** `Memory<byte>` overloads with the new return type rather than changing existing members. Second, `MoveNextAsync()` returns `ValueTask<bool>` even though `Task<bool>` results are already cached: the cache only helps when a step completes synchronously. When a step really waits, a `Task<bool>` would be allocated for every element, so the C# compiler makes the generated async-iterator enumerator implement `IValueTaskSource<bool>` itself and reuses that one object for every step that has to wait. ## What it costs callers Every consumer of the interface inherits the `ValueTask` rules, whichever implementation is plugged in: 1. Await each call **once**, directly. 2. Never attach two awaiters, and never read `.Result` before completion. 3. Call `AsTask()` before `Task.WhenAll`, `Task.WhenAny` or caching. Callers cannot know whether a given implementation pools, so they must assume the strictest case for all of them. A team whose code routinely stores tasks or fans them out may find a `ValueTask` interface a constant source of review comments. ## Implementing such an interface well Most implementers need none of the advanced machinery: - Return `new ValueTask<int>(count)` or `ValueTask.FromResult(count)` when the answer is already known. - Return `ValueTask.FromCanceled<int>(cancellationToken)` when the token is already cancelled, and `ValueTask.FromException<int>(exception)` for an immediate failure. - Write a normal `async ValueTask<int>` method for the genuinely asynchronous path. - Build a pooled `IValueTaskSource<int>` only after measurement shows the asynchronous path's allocation matters, because it brings the reset-and-reuse bookkeeping with it. ## Changing an existing signature Switching an interface member from `Task<int>` to `ValueTask<int>`, or back, is a **breaking change** at several levels: - **Binary**: the member's signature changes, so assemblies compiled against the old one fail at run time, typically with `MissingMethodException`, until they are recompiled. - **Source**: callers that pass the result to `Task.WhenAll`, call `ContinueWith`, or store it as `Task<int>` no longer compile. - **Behavioural**: callers that awaited the result twice still compile and may now misbehave with pooled implementations. That is why the safer evolution is the one `Stream` chose: add a new member with the new return type, and give the base class or a default implementation a sensible fallback. ## A decision checklist for an abstraction 1. Is the member called at high volume, per element, per message or per buffer, rather than once per request? 2. Will common implementations complete synchronously most of the time, or want to pool their operations? 3. Will callers usually just `await` the call? 4. Are you willing to make this choice permanent for the life of the interface? Yes to all four points toward `ValueTask<int>`; otherwise `Task<int>` keeps the contract simpler for everyone. For a non-generic operation the same reasoning applies to `ValueTask` against `Task`, with one extra note: `Task.CompletedTask` is already a cached instance, so a `Task`-returning method that usually completes synchronously allocates nothing on that path either.

  • Why does IAsyncEnumerator<T>.MoveNextAsync() return ValueTask<bool> when Task<bool> results are already cached?
    The cache covers only steps that finish synchronously. A step that really waits would need a fresh task per element. The compiler-generated enumerator for an async iterator implements `IValueTaskSource<bool>` itself, so a step that has to wait returns a `ValueTask<bool>` backed by that same reusable object, and no task is allocated per element.
  • Can an implementer of a ValueTask<int> interface member just write an async method?
    Yes. `async ValueTask<int> ReadAsync(...)` compiles like any async method. When it completes synchronously the result travels inline; when it really suspends, the default builder allocates a task-backed object, so it costs what `Task<int>` would. Implementers only need custom `IValueTaskSource<int>` pooling when profiling demands it.
  • How would you move an existing Task<int>-returning interface method to ValueTask<int> without breaking consumers?
    Do not change it in place. Add a new member with the new return type, as `Stream` did with its `Memory<byte>` overloads, give it a fallback, such as a default interface implementation or a base-class virtual that wraps the old member's task in `new ValueTask<int>(task)`, and let implementers override it over time.

  • ValueTask cannot be used as the return type of an interface method
  • Changing an interface member from Task<int> to ValueTask<int> is non-breaking because both are awaitable
  • A ValueTask signature forces every implementation to complete synchronously
  • Every implementer of a ValueTask interface must write its own IValueTaskSource pool
  • Re-awaiting an interface's ValueTask is fine because the implementation you tested wraps a Task