I am implementing IAsyncDisposable
which requires me to return a ValueTask
, but sometimes my dispose method has nothing to do. How should I return in this case?
At the moment I'm returning new ValueTask(Task.CompletedTask)
which seems to work but since the point of valueTasks is to avoid creating unnecessary heap objects, I'm sure there should be a simpler and more efficient way.
As you know Task is a reference type and it is allocated on the heap but on the contrary, ValueTask is a value type and it is initialized on the stack so it would make a better performance in this scenario.
An instance created with the parameterless constructor or by the default(ValueTask<TResult>) syntax (a zero-initialized structure) represents a synchronously, successfully completed operation with a result of default(TResult) .
Use Task when you have a piece of code that will always be asynchronous, i.e., when the operation will not immediately complete. Take advantage of ValueTask when the result of an asynchronous operation is already available or when you already have a cached result.
All structs have a default constructor. The default constructor of ValueTask
creates a completed ValueTask
:
var completedValueTask = new ValueTask();
Or alternatively:
ValueTask completedValueTask = default;
Update: The official documentation has been updated with the following note:
An instance created with the parameterless constructor or by the
default(ValueTask)
syntax (a zero-initialized structure) represents a synchronously, successfully completed operation.
You can use ValueTask.CompletedTask
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With