Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET async/await: in this case should I return something?

Tags:

c#

async-await

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?

like image 393
Francesco Bonizzi Avatar asked Jan 27 '16 14:01

Francesco Bonizzi


People also ask

Does await return C#?

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.

What is the return type of async await in C#?

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.

What does async await return?

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.


1 Answers

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 Tasks

like image 154
David Avatar answered Oct 21 '22 01:10

David