Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the ValueTask equivalent of Task.CompletedTask?

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.

like image 337
Andy Avatar asked Mar 28 '20 10:03

Andy


People also ask

What is the difference between task and ValueTask?

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.

What is a ValueTask?

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) .

Where can I use ValueTask?

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.


2 Answers

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.

like image 131
Theodor Zoulias Avatar answered Oct 01 '22 07:10

Theodor Zoulias


.NET 5.0:

You can use ValueTask.CompletedTask.

like image 43
Pang Avatar answered Oct 01 '22 07:10

Pang