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.
Task, for an async method that performs an operation but returns no value. Task<TResult>, for an async method that returns a value.
Async functions always return a promise. If the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise. Note: Even though the return value of an async function behaves as if it's wrapped in a Promise.resolve , they are not equivalent.
If you use await in your code, you are required to use the async keyword on the method. If you use async and want to return an actual type, you can declare that your method returns the type as a generic Task like this Task<int> . Task<TResult> , for an async method that returns a value.
The call to the async method starts an asynchronous task. However, because no Await operator is applied, the program continues without waiting for the task to complete. In most cases, that behavior isn't expected.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With