30

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.
2
  • Side note - if its possible, then introduce separate interface which does not have async operations (ISP principle) Commented May 9, 2014 at 9:24
  • 2
    @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
    Commented May 9, 2014 at 9:28

2 Answers 2

36

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

27

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.

6
  • 5
    +1. I like Task.FromResult<object>(null), but the .NET team tends to prefer Task.FromResult(0). Neither of those are cached, though. Commented May 9, 2014 at 11:01
  • 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
    Commented May 9, 2014 at 11:25
  • @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
    Commented May 9, 2014 at 11:28
  • @Noseratio - yes, I figured as much... So my current approach will be private static Task _CompletedTask = Task.Delay(0); public static Task CompletedTask { get { return _CompletedTask; } } which also enables me to replace the implementation in case in future Task.Delay(0) is no longer a no-op.
    – Knaģis
    Commented May 9, 2014 at 11:31
  • @Noseratio, I wonder why you highlighted the fact that your preferred approach returns unique task objects - I currently can't figure out a scenario where in my code the reference equality of tasks would be important...
    – Knaģis
    Commented May 9, 2014 at 11:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.