Pregunta

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.
¿Fue útil?

Solución 2

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.

Otros consejos

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

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top