0

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

CorrieJanse
  • 2,374
  • 1
  • 6
  • 23
  • 3
    The method `GetEntitiesAsync` is defined as returning a `Task>`. The method `GetAllAsync` presumably also returns a `Task>` - so why wouldn't it work? It's just a totally normal, bog-standard method at that point - it works for the same reason `public int GetNumber() => 42` works... – RB. Oct 13 '21 at 22:30
  • in fact if you only have one await and it also is the return value then code analyzer will complain; it's not necessary to use async/await in that case. So in this case, 2 is preferred – Omar Abdel Bari Oct 13 '21 at 22:34
  • 2
    This needs to be closed as a duplicate. for reference https://blog.stephencleary.com/2016/12/eliding-async-await.html Also note, removing the await has differences and can potentially cause issues unless you know what you are doing and/or its a simple task forward – TheGeneral Oct 13 '21 at 22:39
  • Regarding my earlier note the async fixer package speaks of this. https://github.com/semihokur/AsyncFixer . see AsyncFixer01. If you use disassembly tools you'll see the difference under the hood. It does come at a cost. – Omar Abdel Bari Oct 13 '21 at 22:41

1 Answers1

-1

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

ThisGuy
  • 2,335
  • 1
  • 28
  • 34