Value Task vs Task
When should you use ValueTask instead of Task in C#?
Answers use simple, clear English.
Audio N/AQuick interview answer
Use ValueTask when the operation often completes synchronously (cache hits, pooled results) and you want to avoid allocating a Task object. Prefer Task for most public APIs because ValueTask has more usage constraints.
Detailed answer
Use ValueTask when the operation often completes synchronously (cache hits, pooled results) and you want to avoid allocating a Task object. Prefer Task for most public APIs because ValueTask has more usage constraints. ValueTask is a discriminated union of a completed result or a Task. Consuming it more than once, awaiting concurrently, or blocking with GetAwaiter().GetResult() is unsafe unless you understand the rules. .NET libraries use it in hot paths like Channel readers and Memory caches.
Full explanation
ValueTask is a discriminated union of a completed result or a Task. Consuming it more than once, awaiting concurrently, or blocking with GetAwaiter().GetResult() is unsafe unless you understand the rules. .NET libraries use it in hot paths like Channel readers and Memory caches.
Code example
public ValueTask<int> GetCachedAsync(string key)
{
if (_cache.TryGetValue(key, out int value))
return ValueTask.FromResult(value);
return new ValueTask<int>(LoadFromDbAsync(key));
}Common mistakes
Using ValueTask everywhere 'for performance' without measuring; awaiting twice; storing ValueTask in fields.
Best practices
Default to Task for public APIs. Use ValueTask only in hot internal paths after profiling.
Follow-up questions
- What happens if you await a ValueTask twice?
- How does IValueTaskSource work?