In C#, what is ValueTask<TResult>, and how should code that calls a ValueTask-returning method normally consume it?
answer
- a struct, not a class
- three things it can wrap
- the simplest consumption wins
- await once, right away
basics
~10 sValueTask<TResult> is a readonly struct that wraps either an already available result, a Task<TResult>, or an IValueTaskSource<TResult>. Callers should await it directly, exactly once, as soon as they get it.
solid answer
~40 s`ValueTask<TResult>` is a `readonly struct` in `System.Threading.Tasks` that a method can return instead of `Task<TResult>`. It wraps one of three things: a result that was ready immediately, a `Task<TResult>`, or an `IValueTaskSource<TResult>` object that may be pooled and reused for later operations. Because of that last case, the caller treats it as a one-shot handle: `int read = await reader.ReadAsync(buffer);` and nothing else. Storing it to await later, awaiting it twice, or reading `.Result` before it has finished can fail once the object behind it is reused. When you genuinely need a task you can share or pass to `Task.WhenAll`, call `AsTask()` once and work with the `Task<TResult>`. The non-generic `ValueTask` follows the same rules for operations with no result.
go deeper
Recall that ValueTask<TResult> is a struct you can return instead of Task<TResult>, and that the caller's job is simply to await it once, immediately.
Explain the three forms it can wrap and why the reusable IValueTaskSource form turns double awaits and early Result reads into bugs; name AsTask as the escape hatch.
Show you would spot a stored or re-awaited ValueTask in review and know which BCL APIs, such as Stream.ReadAsync over Memory<byte>, already hand you one.
Frame ValueTask as a contract the caller signs: cheaper results in exchange for one-shot consumption, and weigh whether a codebase's callers are disciplined enough to honour it.
## What ValueTask<TResult> is `System.Threading.Tasks.ValueTask<TResult>` is a **`readonly struct`** that represents the result of an asynchronous operation. A method can declare it as its return type exactly where it would otherwise declare `Task<TResult>`, and it can be marked `async` like any `Task`-returning method. A non-generic **`ValueTask`** exists for operations that produce no value. The difference from `Task<TResult>` is that `Task<TResult>` is a **class**: every instance that is not served from a cache is a heap object. `ValueTask<TResult>` is a value: when the answer is already known, the struct simply carries the answer and no task object exists at all. ## The three things it can wrap A `ValueTask<TResult>` holds exactly one of these at a time: | Wrapped form | Created by | Typical case | |---|---|---| | The result itself | `new ValueTask<TResult>(result)` or an `async` method that finished without suspending | data already sitting in a buffer | | A `Task<TResult>` | `new ValueTask<TResult>(task)` or an `async` method that really awaited | ordinary asynchronous work | | An `IValueTaskSource<TResult>` plus a `short` token | `new ValueTask<TResult>(source, token)` | a pooled, reusable operation object | The third form is what makes `ValueTask` different in kind, not just in size. An `IValueTaskSource<TResult>` object can be **reset and reused** for the next operation once its current result has been read, and the `short` token tells the source which operation a given `ValueTask` refers to. ## How to consume it: await it, once The runtime's own documentation for `ValueTask<TResult>` says instances "are meant to be directly awaited". In practice: - **Await it immediately**: `int read = await stream.ReadAsync(buffer);` - **Await it exactly once.** After the result has been retrieved, a pooled source may already be serving a different operation. - **Do not await it from two places at the same time**; a source is not required to accept more than one continuation. - **Do not read `.Result` or call `GetAwaiter().GetResult()` until `IsCompleted` is true**; a pooled source may throw instead of waiting. - **Do not discard it.** Ignoring the returned value is, in the words of code analysis rule CA2012, likely a functional bug that may also degrade performance. `ValueTask<TResult>` also exposes `ConfigureAwait(bool)`, so `await reader.ReadAsync(buffer).ConfigureAwait(false)` is still a single direct await. When to pass `false` is covered in the lesson on synchronization contexts. ## When you need more than one await Some code legitimately needs a task it can keep: caching it, awaiting it from two places, or handing it to `Task.WhenAll`, which accepts `Task` objects. For those cases: 1. Call **`AsTask()`** once. It returns the wrapped `Task<TResult>` if there is one, and otherwise produces a task that represents the operation. 2. Use the resulting `Task<TResult>` as freely as any other task. 3. Never touch the original `ValueTask<TResult>` again. `Preserve()` is the same idea when you want to keep the `ValueTask<TResult>` type: it returns a `ValueTask<TResult>` that "may be used at any point in the future". ## Patterns to flag in a code review Each of these compiles cleanly and may pass tests, yet breaks the one-shot rule: - `var pending = reader.ReadAsync(buffer);` followed by **two** `await pending;` statements, for example one inside a logging helper. - `_ = reader.ReadAsync(buffer);` which **discards** the value, so nobody observes its result or its exception. - A synchronous helper that returns `reader.ReadAsync(buffer).Result` without first checking `IsCompleted`. - A `List<ValueTask<int>>` filled in a loop and awaited later, which keeps many single-use values alive longer than intended. The repair is the same each time: await directly, or convert with `AsTask()` at the moment the value is received. ## ValueTask<TResult> compared with Task<TResult> | Question | `Task<TResult>` | `ValueTask<TResult>` | |---|---|---| | Kind of type | class | readonly struct | | Await more than once | yes | no | | Several awaiters at once | yes | no | | Pass to `Task.WhenAll` | directly | after `AsTask()` | | Allocation when the result is ready | a task object unless the runtime serves a cached one | none | ## Where you meet it You rarely have to choose `ValueTask` yourself to run into it. `Stream.ReadAsync(Memory<byte>, CancellationToken)` returns `ValueTask<int>`, `Stream.WriteAsync(ReadOnlyMemory<byte>, CancellationToken)` returns `ValueTask`, and `IAsyncEnumerator<T>.MoveNextAsync()` returns `ValueTask<bool>`. Asynchronous disposal also returns `ValueTask`, and is covered in its own lesson. In every one of these, the calling rule is the same: await the call directly and move on.
- What is the non-generic ValueTask for, and what does ValueTask.CompletedTask return?`ValueTask` represents an asynchronous operation with no result, as `Task` does; `Stream.WriteAsync(ReadOnlyMemory<byte>, CancellationToken)` returns one. `ValueTask.CompletedTask` is simply `default(ValueTask)`, a value that represents a successfully finished operation and allocates nothing. The same consumption rules apply: await it once, directly.
- Can you call ConfigureAwait on a ValueTask<TResult>, and is that still a direct await?Yes. `ValueTask<TResult>` has `ConfigureAwait(bool continueOnCapturedContext)`, which returns a `ConfiguredValueTaskAwaitable<TResult>`; writing `await vt.ConfigureAwait(false)` still consumes it once. Unlike `Task`, it has no overload that takes `ConfigureAwaitOptions`, so code that needs those options must call `AsTask()` first.
- ValueTask is a class that wraps Task to make it faster
- A ValueTask can be awaited as many times as a Task can
- Reading ValueTask.Result is always safe because it blocks like Task.Result
- You can pass a ValueTask straight into Task.WhenAll
- Returning ValueTask forces the method to run synchronously