简体   繁体   中英

Async await vs simple execution

Is there any benefit executing a function using async Task await over executing in the current thread?

[HttpGet]
[Route("example/{id}")]
public async Task<Example> GetExample(int id)
{
    return await exampleService.GetExampleAsync(id);
}

Compared to:

[HttpGet]
[Route("example/{id}")]
public Example GetExample(int id)
{
    return exampleService.GetExampleAsync(id).Result;
}

Yes, the call without await is going to block your execution until the method all finishes.

This is bad, it slows the server down. When you'll use await keyword, the .Net framework is going to let things run so that the next request can be processed.

It will return the response to the caller as soon as the processing will finish. Besides, async/await is new agey man! thin I hope this helps

The primary difference between your two samples is that the second is synchronous and blocking. There's no good reason to block on async code, as has been covered many other places. Your first example however needlessly generates a state machine to handle the unnecessary async pieces. If you have nothing to do after an await within an async method simply return the Task :

[HttpGet]
[Route("example/{id}")]
public Task<Example> GetExample(int id)
{
    return exampleService.GetExampleAsync(id);
}

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