-1

There is any difference between these cases where i use async/await.

In the first case im awaiting for the service Task to complete and then return the value.

    [HttpGet]
    public async Task<IEnumerable<Post>> Get()
    {
       return await PostsService.GetAll(); // returns Task
    }

In this case i return the Task without awaiting for the data to be resolved.

    [HttpGet]
    public Task<IEnumerable<Post>> Get()
    {
       return PostsService.GetAll(); // returns Task
    }

These two cases works without any errors. So im not sure if its correct to return directly without awaiting or there may be any issues.

hawks
  • 861
  • 1
  • 8
  • 20
  • [Relevant](https://blog.stephencleary.com/2016/12/eliding-async-await.html); short answer: in this case, they're practically the same (minor difference in exception behavior if `PostsService` is `null`). But beware of eliding `async`/`await` in anything but the simplest methods. – Stephen Cleary Apr 02 '20 at 12:56

1 Answers1

0

They are the same in terms of behavior. The problem is that the async method will be converted into it's own class, and then create a state machine to execute the call. That means that a lot more IL/assembly code will be executed in that case

Is that a real performance issue? To be honest for 95% of cases I don't think so, you will not notice it. If you are building a heavily used code where every line matters, then go for the second one

You can read this if you want more info: https://weblogs.asp.net/dixin/understanding-c-sharp-async-await-1-compilation

Carlos Garcia
  • 2,771
  • 1
  • 17
  • 32