简体   繁体   中英

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

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 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

Task is the new void !

Regarding async methods!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM