If my interface must return Task what is the best way to have a no-operation implementation?
Today, I would recommend using Task.CompletedTask to accomplish this.
Pre .net 4.6:
Using Task.FromResult(0)
or Task.FromResult<object>(null)
will incur less overhead than creating a Task
with a no-op expression. When creating a Task
with a result pre-determined, there is no scheduling overhead involved.
To add to Reed Copsey's answer about using Task.FromResult
, you can improve performance even more if you cache the already completed task since all instances of completed tasks are the same:
public static class TaskExtensions
{
public static readonly Task CompletedTask = Task.FromResult(false);
}
With TaskExtensions.CompletedTask
you can use the same instance throughout the entire app domain.
The latest version of the .Net Framework (v4.6) adds just that with the Task.CompletedTask
static property
Task completedTask = Task.CompletedTask;
Task.Delay(0)
as in the accepted answer was a good approach, as it is a cached copy of a completed Task
.
As of 4.6 there's now Task.CompletedTask
which is more explicit in its purpose, but not only does Task.Delay(0)
still return a single cached instance, it returns the same single cached instance as does Task.CompletedTask
.
The cached nature of neither is guaranteed to remain constant, but as implementation-dependent optimisations that are only implementation-dependent as optimisations (that is, they'd still work correctly if the implementation changed to something that was still valid) the use of Task.Delay(0)
was better than the accepted answer.
Recently encountered this and kept getting warnings/errors about the method being void.
We're in the business of placating the compiler and this clears it up:
public async Task MyVoidAsyncMethod()
{
await Task.CompletedTask;
}
This brings together the best of all the advice here so far. No return statement is necessary unless you're actually doing something in the method.
return Task.CompletedTask; // this will make the compiler happy