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.
public ValueTask<int> GetAsync(string key) => cache.TryGetValue(key, out int v) ? new ValueTask<int>(v) : new ValueTask<int>(LoadAsync(key));
Try it
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.
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
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
ValueTaskmust be awaited (or converted withAsTask) at most once. Do not call.Result,.GetAwaiter().GetResult(), orawaiton an incomplete one more than once, and do not use it from multiple consumers. - No blocking. Never block on a
ValueTaskthat is not yet complete. UseAsTask()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 throughPoolingAsyncValueTaskMethodBuilder). - Best for hot paths. Use it when profiling shows task allocations matter and when most calls complete synchronously. For public libraries, prefer
Taskunless the benefit is measurable. - Combinators need Tasks.
Task.WhenAllandWhenAnyacceptTask, so callAsTask()first. - Interfaces.
IAsyncEnumerator<T>.MoveNextAsyncandIAsyncDisposable.DisposeAsyncreturnValueTaskfor this reason. - Struct size. A
ValueTask<T>is larger than a reference. Passing it around has a small cost.