Assume I have a method that is not async but returns a Task
(because the definition is from an interface intended also for async implementations)
public Task DoWorkAsync(Guid id)
{
// do the work
return ...;
}
What is the best object to return? My current options:
return Task.Yield();
return Task.FromResult<object>(null);
// any of the other but cached in a static field and reused.
You can't return Task.Yield()
, it's not a Task
but YieldAwaitable
for use with await
, and it actually introduces asynchrony (I posted some more details here).
I use Task.FromResult(Type.Missing)
for this purpose. Perhaps, the most efficient, albeit undocumented option is Task.Delay(0)
, it returns a static completed task.
Task.Delay(0)
. We can cache it, if we want to. - noseratioTask.FromResult<object>(null)
, but the .NET team tends to prefer Task.FromResult(0)
. Neither of those are cached, though. - Stephen Cleary0x4000
will always mean "do not dispose" and thus create and cache new Task(false, (TaskCreationOptions)0x4000, System.Threading.CancellationToken.None)
yourself... - Knaģis
In Microsoft.net 4.6, the Task class has a static property for this purpose.
Task.CompletedTask
https://msdn.microsoft.com/en-us/library/system.threading.tasks.task.completedtask(v=vs.110).aspx