Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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. 
like image 798
Knaģis Avatar asked May 09 '14 09:05

Knaģis


People also ask

What does a task method return?

Task, for an async method that performs an operation but returns no value. Task<TResult>, for an async method that returns a value.

What does an async task return?

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.

Can we use task without async?

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.

What happens if you do not await an async method?

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.


2 Answers

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

like image 109
Kepboy Avatar answered Oct 06 '22 00:10

Kepboy


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.

like image 32
noseratio Avatar answered Oct 06 '22 01:10

noseratio