02/10/2019
Introduction
ValueTask has been recently introduced to C# to comprehend use-cases where allocation of a Task would be a problem. When it comes to deciding whether to use Task or ValueTask it is always suggested to measure the given application code path.
When a Task is awaited a state machine is being generated by the compiler. This state machine (a struct) executes through the asynchronous states of the method, also it preserves the internal state of the method. When we hit a state where we need to await another task, this struct will become boxed, so the state can be preserved between different threads that might execute different states of the method. When we execute synchronously though, no boxing would be required. However, the Task we return still needs to be allocated. The class library tries its best to use cached tasks, still we might hit a case where a new Task is being allocated. To avoid this allocation we can use ValueTask. Here are some remarks of the ValueTask documentation:
A method may return an instance of this value type when it's likely that the result of its operation will be available synchronously, and when it's expected to be invoked so frequently that the cost of allocating a new Task for each call will be prohibitive.
Find out more