29

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.

Andy
  • 10,412
  • 13
  • 70
  • 95

2 Answers2

42

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.

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
17

.NET 5.0:

You can use ValueTask.CompletedTask.

Pang
  • 9,564
  • 146
  • 81
  • 122