C# Interview Question #144

What is ValueTask<T>, and when should it be used?

Advanced Async, Parallelism & Threading Senior Advanced

Quick Interview Answer

ValueTask<T> is an awaitable value type that can represent either an already available result or an asynchronous operation.

Detailed Explanation

ValueTask<T> is an awaitable value type that can represent either an already available result or an asynchronous operation.

It can reduce Task allocations in specialized high-performance scenarios where operations frequently complete synchronously. However, ValueTask has more usage rules and complexity than Task.

For most application services and APIs, Task<T> should remain the default. ValueTask<T> should normally be introduced only when profiling demonstrates that Task allocation is significant or when implementing APIs where it is naturally appropriate.

Code Example

public ValueTask<int> GetCountAsync()
{
    if (_cachedCount.HasValue)
        return ValueTask.FromResult(_cachedCount.Value);

    return LoadCountAsync();
}