Warm tip: This article is reproduced from serverfault.com, please click

Why does shorthand for asynchronous functions work without having async or await?

发布于 2021-10-13 22:28:14

When writing async functions, usually if you do not explicitly writer await or async your compiler would throw an error or warning. Example of correct syntax below:

public async Task<List<TEntity>> GetEntitiesAsync() =>
            await TEntityRepository.GetAllAsync();

Now the following works still, it is async and returns a Task<List>

public Task<List<TEntity>> GetEntitiesAsync() =>
            TEntityRepository.GetAllAsync();

Why does the second one still work

Questioner
CorrieJanse
Viewed
0
ThisGuy 2021-10-14 06:49:56

Both calls return the same Task, so they are the effectively the same.

In order to use "await" in a method, that method MUST be labeled async. Since the second one doesn't use await, it doesn't need to be labeled async.

That's it.

With that said, it probably isn't a good ideas to do this as there are some pitfalls as described in the article mentioned by @TheGeneral: https://blog.stephencleary.com/2016/12/eliding-async-await.html