简体   繁体   中英

What to return from non-async method with Task as the return type?

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.

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM