Sobes.tech
Junior — Middle

How to distinguish between Task and ValueTask and when to use them?

sobes.tech AI

Answer from AI

Task and ValueTask are types used for asynchronous programming in C#.

  • Task is a reference type representing an asynchronous operation. It is always allocated on the heap and is suitable for most asynchronous code scenarios.

  • ValueTask is a value type (struct) that can contain either the result of an operation or a reference to a Task. It is designed for optimization when an asynchronous operation often completes synchronously and does not require heap allocation.

When to use:

  • Use Task by default — it is simpler and safer.
  • Use ValueTask if the method often completes synchronously and you want to avoid unnecessary allocations, for example, in high-performance libraries.

Important:

  • ValueTask cannot be reused — it cannot be awaited multiple times.
  • If a method returns a ValueTask and you want to get a Task, you can call .AsTask().

Example:

// Method with Task
async Task<int> GetValueAsync() {
    await Task.Delay(100);
    return 42;
}

// Method with ValueTask
ValueTask<int> GetValueFastAsync(bool fast) {
    if (fast) return new ValueTask<int>(42); // synchronous result
    else return new ValueTask<int>(GetValueAsync()); // asynchronous
}
How to distinguish between Task and ValueTask and… - sobes.tech