Reputation: 125
Action in Controller is already in a different thread, why do we still need to use async/await? I was looking at: https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-3.1&tabs=visual-studio#examine-the-posttodoitem-create-method I see it has a action in this controller: [HttpPost] public async Task> PostTodoItem(TodoItem todoItem)
So, I did a few test in my own controller, I see when I send a request from my browser, the server side always create a new worker thread to handle the request, so that's why I had the doubt: if the controller is already handling request in different thread, why should I still use async/await? Since the request being handled in a new thread, I don't think it will block any other request.
Upvotes: 1
Views: 683
Reputation: 81593
The async and await pattern is about scalability. Why block a thread when you can use an IO completion port? It's as simple as that.
The async and await pattern offloads the work (term used loosely) and allows the threadpool to potentially recover the thread and use it elsewhere until your IO work completes.
You might not notice a difference now, but when you start to scale a website to 1000s of concurrent jobs, efficiently using resources will start to matter a lot. One of those tools you can use, is... the async and await pattern.
Note : this is a simplistic response to a simplistic question on a complex and nuanced topic. Without writing a thesis on the internal workings of a language feature and its uses, it's probably a good place for you to start researching the async and await pattern to answer some of the most common questions for your self, you'll have fun and gain a sense of achievement :)
Upvotes: 8