skip to content

A C# ValueTask<int> from a pooled reader works on its first await but throws InvalidOperationException when awaited again; what rule was broken, and how do you fix it?

level: seniorimportance: should knowfreq 40%

answer

  1. the object behind the struct
  2. reset and reused after GetResult
  3. a short token as version
  4. once, never concurrently, no early Result
  5. AsTask or Preserve

basics

~20 s

A ValueTask must be consumed once: one await, never concurrent awaits, no Result before completion. A pooled IValueTaskSource is reused once its result is read, so the stale token is rejected; await once, or use AsTask() or Preserve().

solid answer

~40 s

The `ValueTask<int>` wraps an `IValueTaskSource<int>` and a `short` token. Once the first await reads the result, the source is free to `Reset()` and serve the next read, which bumps its version. The second await presents the old token; a source built on `ManualResetValueTaskSourceCore<int>` compares it with the current version and throws `InvalidOperationException`. The runtime's documentation calls reusing such a `ValueTask` undefined behaviour, so a looser source could even return another operation's data. The rules are: await once; never attach two awaiters; never read `.Result` or `GetAwaiter().GetResult()` before `IsCompleted`. The fix is to await it once and keep the `int`, or, when the operation really must be awaited from several places, call `AsTask()` or `Preserve()` once and use only that. Analyzer rule CA2012 flags these patterns, though only as a suggestion by default.

code

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

var source = new ReusableReadSource();
ValueTask<int> read = source.StartRead(42);

Console.WriteLine($"first await: {await read}");
ValueTask<int> next = source.StartRead(99); // the same object is reused for the next read

try
{
    Console.WriteLine($"second await: {await read}");
}
catch (InvalidOperationException)
{
    Console.WriteLine("second await threw InvalidOperationException");
}
Console.WriteLine($"next read: {await next}");

// One reusable object backs many ValueTask<int> values, told apart by a short token.
sealed class ReusableReadSource : IValueTaskSource<int>
{
    private ManualResetValueTaskSourceCore<int> _core;

    public ValueTask<int> StartRead(int bytes)
    {
        _core.Reset();                   // bumps the version, invalidating older tokens
        short token = _core.Version;
        ThreadPool.QueueUserWorkItem(_ => _core.SetResult(bytes));
        return new ValueTask<int>(this, token);
    }

    public int GetResult(short token) => _core.GetResult(token);
    public ValueTaskSourceStatus GetStatus(short token) => _core.GetStatus(token);
    public void OnCompleted(Action<object?> continuation, object? state, short token,
        ValueTaskSourceOnCompletedFlags flags) => _core.OnCompleted(continuation, state, token, flags);
}

go deeper

for a junior

Recall the one rule that prevents this bug: a ValueTask is awaited once, directly, and the value is kept rather than the ValueTask.

for a middle

Explain the IValueTaskSource and token mechanism, and why Reset() makes an old ValueTask stale after its result has been read.

for a senior

Diagnose why tests pass while production fails, choose between keeping the result, AsTask() and Preserve(), and make CA2012 part of the build.

for a principal

Weigh the reliability risk a ValueTask-returning API pushes onto every caller, and decide whether reviews and analyzers can carry that risk across teams.

## The symptom A team replaces `Task<int>` with `ValueTask<int>` on a reader whose implementation pools its operation objects. Code that awaited the same read twice, once to log it and once to use it, worked for years with `Task<int>`. Now the first await returns the byte count and the second throws **`InvalidOperationException`**, or, with a different implementation, returns a number that belongs to a later read. ## Why a ValueTask can be single-use A `ValueTask<int>` is a struct holding one of three things: the result itself, a `Task<int>`, or an **`IValueTaskSource<int>`** together with a **`short` token**. The third form exists so that one long-lived object can back many operations without allocating per operation: - the source exposes `GetStatus(short token)`, `OnCompleted(...)` and `GetResult(short token)`; - the token identifies *which* operation a particular `ValueTask` refers to; - after `GetResult` has been called, the source may be **reset and reused**. `ManualResetValueTaskSourceCore<TResult>`, the BCL helper most implementations are built on, keeps a `short` version. `Reset()` increments it, and `GetResult` and `GetStatus` throw `InvalidOperationException` when the presented token does not match. The `ValueTask<TResult>` documentation states the general rule: once the result has been retrieved, "do not attempt to retrieve it again", because the source "may use the act of retrieving the instances result as a notification that the instance may now be reused", and reusing the `ValueTask` "results in undefined behavior". A source that skips the version check could therefore hand back another operation's result. ## The three consumption rules 1. **Await once.** Retrieve the result a single time and keep the value, not the `ValueTask`. 2. **Never await concurrently.** Do not register two continuations; `ManualResetValueTaskSourceCore<TResult>.OnCompleted` throws `InvalidOperationException` if a second continuation arrives before completion. 3. **No blocking reads before completion.** `.Result` and `GetAwaiter().GetResult()` on a source-backed `ValueTask` do not wait themselves: they call the source's `GetResult` directly, and `ManualResetValueTaskSourceCore<TResult>` throws because the operation has not completed. | Wrapped form | Second await | Two awaiters at once | `.Result` while pending | |---|---|---|---| | Result inline | works, by accident | works | not possible, already complete | | `Task<int>` | works, as with any task | works | blocks until done | | Pooled `IValueTaskSource<int>` | undefined; throws with the BCL helper | undefined; throws with the BCL helper | undefined; throws with the BCL helper | The table explains why the bug hides: a unit test whose fake reader returns `new ValueTask<int>(value)` passes, and only the pooled production implementation fails. ## Where the second consumption usually hides The double use is rarely two adjacent `await` lines. It tends to come from structure around the call: - a **logging or metrics decorator** that awaits the value to record timing and then returns the same `ValueTask<int>` to its caller; - a **retry helper** that receives the value as a parameter and awaits it again on each attempt; - a **cache** such as a dictionary of pending reads, where every lookup awaits the stored value; - a hand-written **race**, where two branches each await the same value. Search for `ValueTask` stored in a field, a collection, a parameter or a closure; each is a place it can be consumed twice. ## Fixing it - **Await once and keep the `int`**: `int read = await reader.ReadAsync(buffer); Log(read); Use(read);` This is almost always the right repair. - **`AsTask()`** when you need a `Task<int>`: for `Task.WhenAll`, `Task.WhenAny`, a cache, or several awaiters. It returns the wrapped task if there is one; for a source-backed value it builds a task that represents the operation. - **`Preserve()`** when you want to keep the `ValueTask<int>` type: it returns the same value unchanged if the result was inline, and otherwise a `ValueTask<int>` wrapping `AsTask()`, which "may be used at any point in the future". Call either one **once, immediately**, and never touch the original value again; calling `AsTask()` after the first await is already too late. ## Catching it before production - Code analysis rule **CA2012, "Use ValueTasks correctly"**, flags a `ValueTask` returned from a member call that is consumed more than once, read before completion, or discarded. It is reported only as a suggestion by default, so a team that relies on it raises its severity; how to do that is covered with compiler warnings and analyzers. - In review, treat a `ValueTask` stored in a local, a field or a collection as suspicious unless the next line awaits it.

  • Why did the same double await pass every unit test?
    The fake reader returned `new ValueTask<int>(value)`, or an async method that wrapped a `Task<int>`. Both forms tolerate repeated awaits. The rule is about what a `ValueTask` *may* wrap, so the bug shows only against an implementation backed by a reusable `IValueTaskSource<int>`. Write the test against the real pooled source, or enable CA2012 at warning level.
  • Is GetAwaiter().GetResult() an acceptable way to block on a ValueTask<int>?
    Only when `IsCompleted` is already true. CA2012's description warns that reading a result before it is known to be completed may cause an exception or corruption, and `ManualResetValueTaskSourceCore<TResult>` throws `InvalidOperationException` instead of waiting. If synchronous waiting is truly unavoidable, call `AsTask()` first and block on the task; the deadlock risks of blocking at all are covered with synchronization contexts.
  • When is calling AsTask() too late?
    After the `ValueTask` has been awaited or its result read. `AsTask()` itself asks the source for status and result using the stored token, so once the source has been reset for another operation it is as stale as a second await. Convert at the moment you receive the value.

A coat-check tag that the cloakroom hangs back on the hook as soon as you collect your coat: show the same tag again and you are either turned away or handed the next guest's coat.

  • A ValueTask can be awaited twice exactly like a Task
  • Two methods may await the same ValueTask concurrently if the source is thread-safe
  • ValueTask.Result always blocks until the operation finishes, like Task.Result
  • If the double await passes unit tests with a fake reader, it is safe
  • Copying the ValueTask struct gives each copy its own independent operation
  • Calling AsTask() after the first await makes later awaits safe