Reputation: 195
I'm testing out the impact of using async and await as I understand it is supposedly able to run multiple calls by not blocking a thread.
I used this link as my reference
The following is my code on the controller :
[Route("api/email")]
public class EmailController : Controller
{
private ContentManagement _contentManagement;
public EmailController(ContentManagement contentManagement)
{
_contentManagement = contentManagement;
}
[HttpGet("async")]
public async Task<IActionResult> GetAsync()
{
DateTime cur = DateTime.Now;
var name = await _contentManagement.GetNameAsync();
return Ok($"Value : {name} \nStarted : {cur.TimeOfDay}\n Ended : {DateTime.Now.TimeOfDay}");
}
[HttpGet("normal")]
public IActionResult Get()
{
DateTime cur = DateTime.Now;
var name = _contentManagement.GetName();
return Ok($"Value : {name} \nStarted : {cur.TimeOfDay}\n Ended : {DateTime.Now.TimeOfDay}");
}
}
The contentManagement class is exactly the same as provided in the link above.
I find that when I call the async web apis simultaneously, they perform exactly the same as the sync web api by performing the tasks sequentially.
Here are my results :
Anyone can provide feedback if I'm missing something or did something wrong?
UPDATE: - So when I tried it on two devices, one on my computer and another on my phone, it seems that they run simultaneously (regardless if it's an async / await or just a normal sync method); - If it's on the same device, they run sequentially (as shown in the image above)
Upvotes: 3
Views: 1509
Reputation: 16801
The main reason to run code async is to efficient the use of compute resources. Async is not a miracle line of code that will make some other code run faster.
In your case, when using async-await you will mainly efficient the use of threads in the thread pool. Let's go through this by a simplified explanation.
If we take a look at your sync method first. When your thread reaches this line var name = _contentManagement.GetName();
it will wait until it returns a name. In the processing time of GetName(), the thread will absoultely do nothing. It will just be locked waiting on the response.
The async method however; When your thread reaches this line var name = await _contentManagement.GetNameAsync();
it will know that this method is marked await
and then the thread is free to return to the thread pool to serve other stuff meanwhile the GetNameAsync
processing. Then when the GetNameAsync
is completed a thread will be served from the thread pool to continue the next line.
In this way we can perform the same logic but use less resources doing so (we save thread time when processing external async calls)
Upvotes: 3
Reputation: 14846
async-await
will not make it faster. In fact, it will make it slower.
The real benefit is responsiveness. Releasing the UI thread, releasing the thread handling the web request, is etc.
You'll need more than one simultaneous request to see the difference.
Upvotes: 1