13

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.


  • Side note - if its possible, then introduce separate interface which does not have async operations (ISP principle) - Sergey Berezovskiy
  • @SergeyBerezovskiy - the biggest problem in such case is that the caller has to switch between two interfaces depending on the implementation provided (for example, by IoC). I could create a wrapper in between but for it the original question is still important. - Knaģis

2 답변


17

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.


  • I would go with the former, for readability. - Yuval Itzchakov
  • @YuvalItzchakov, me too. It also returns a unique tasks, unlike Task.Delay(0). We can cache it, if we want to. - noseratio
  • +1. I like Task.FromResult<object>(null), but the .NET team tends to prefer Task.FromResult(0). Neither of those are cached, though. - Stephen Cleary
  • I like the undocumented option. I wonder how safe it is to assume that 0x4000 will always mean "do not dispose" and thus create and cache new Task(false, (TaskCreationOptions)0x4000, System.Threading.CancellationToken.None) yourself... - Knaģis
  • @Knaģis, that probably would be a bad idea, they can change it any time :) Plus, this constructor override is private, you'd need to use reflection. - noseratio

19

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

Linked


Related

Latest