C# › Asynchronous Programming
What is ValueTask<T> and when should you use it instead of Task<T> for performance?
AdvancedAnswer
ValueTask<T> is a struct that can represent EITHER a synchronously-already-available result OR an in-progress asynchronous operation, avoiding a heap allocation entirely in the common case where a method often completes synchronously (like a cache hit) — but it comes with important usage restrictions (like not awaiting it twice) that Task<T> doesn't have.
public ValueTask<int> GetCachedValueAsync(string key) {
if (cache.TryGetValue(key, out int value)) {
return new ValueTask<int>(value); // synchronous path: zero Task allocation
}
return new ValueTask<int>(FetchAndCacheAsync(key)); // genuinely async path
}Real-world example Optimizing a frequently-called caching layer where most calls hit the cache and complete synchronously, avoiding needless Task allocations.