In a case like this, where my task could return instantly because of certain conditions:
public async Task Test(List<int> TestList)
{
if (TestList.Count() == 0)
return;
// Do something
await UploadListAsync(TestList);
}
Is it correct return;
, should I use Task.FromResult(false);
, or is there a more correct way?
When the asynchronous operation completes, the await operator returns the result of the operation, if any. When the await operator is applied to the operand that represents an already completed operation, it returns the result of the operation immediately without suspension of the enclosing method.
Starting with C# 7.0, an async method can return any type that has an accessible GetAwaiter method that returns an instance of an awaiter type. In addition, the type returned from the GetAwaiter method must have the System. Runtime. CompilerServices.
The behavior of async / await is similar to combining generators and promises. 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.
When you're using an async
, you can't return a Task
explicitly (see edit) - the return value has been boxed up by the compiler to be the return value of the Task
. Thus, your async
methods should behave like other methods and return
if they need to bail out of logic early.
EDIT:
The one time you CAN return a Task
during an async
is if the return type is Task<Task...
, however this would still be returning the inner Task
, not the outer, since the compiler has done the same wrapping. This should also be a fairly rare use case as opposed to await
-ing a chain of Task
s
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