Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Async and Concurrency

ValueTask and ValueTask<T>

Reference for ValueTask and ValueTask<TResult> in C#: avoid allocations when results are often ready, the rules for awaiting once and AsTask.

ValueTask<TResult> is a struct that is either a ready result or a wrapper around a Task<TResult>. When a method usually finishes synchronously, for example because the answer is in a cache, returning a ValueTask<T> avoids allocating a Task on every call. ValueTask (without a type argument) does the same for operations with no result.

It is an optimization with strict usage rules. For ordinary application code, Task and Task<T> remain the right default.

C#
public ValueTask<int> GetAsync(string key) =>
    cache.TryGetValue(key, out int v) ? new ValueTask<int>(v) : new ValueTask<int>(LoadAsync(key));

Try it

C# A cache that avoids allocating tasks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# Await once, or convert with AsTask

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

C#
public readonly struct ValueTask<TResult>
{
    public ValueTask(TResult result);
    public ValueTask(Task<TResult> task);
    public bool IsCompleted { get; }
    public bool IsCompletedSuccessfully { get; }
    public bool IsFaulted { get; }
    public bool IsCanceled { get; }
    public TResult Result { get; }
    public Task<TResult> AsTask();
    public ValueTaskAwaiter<TResult> GetAwaiter();
}

public readonly struct ValueTask
{
    public static ValueTask CompletedTask { get; }
    public static ValueTask<TResult> FromResult<TResult>(TResult result);
}
Member Description
ValueTask<T>(result) A completed value task holding result; allocates nothing.
ValueTask<T>(task) Wraps an existing task.
IsCompletedSuccessfully true when the result is ready and no exception occurred.
AsTask() Returns a Task<T> that can be awaited many times.
Preserve() Returns a value task that may be awaited several times.

Returns: awaiting gives the result of type TResult (nothing for ValueTask).

Errors: stored exceptions are rethrown at the await. Misusing a value task is undefined behavior; see below.

Usage notes

  • The rules. A ValueTask must be awaited (or converted with AsTask) at most once. Do not call .Result, .GetAwaiter().GetResult(), or await on an incomplete one more than once, and do not use it from multiple consumers.
  • No blocking. Never block on a ValueTask that is not yet complete. Use AsTask() first if you must.
  • Allocation can still happen. An async ValueTask<T> method that really suspends still allocates unless the runtime pools its builder (pooling is opt-in through PoolingAsyncValueTaskMethodBuilder).
  • Best for hot paths. Use it when profiling shows task allocations matter and when most calls complete synchronously. For public libraries, prefer Task unless the benefit is measurable.
  • Combinators need Tasks. Task.WhenAll and WhenAny accept Task, so call AsTask() first.
  • Interfaces. IAsyncEnumerator<T>.MoveNextAsync and IAsyncDisposable.DisposeAsync return ValueTask for this reason.
  • Struct size. A ValueTask<T> is larger than a reference. Passing it around has a small cost.