简体   繁体   English

为什么在 Asp.net 核心 web Z8A5DA52ED1206747D359EA70

[英]Why use async/await in an action in controller in Asp.net core web api

Action in Controller is already in a different thread, why do we still need to use async/await? Controller 中的动作已经在不同的线程中,为什么我们还需要使用 async/await? I was looking at: https://docs.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)我在看: https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-3.1&tabs=visual-studio#examine-the-posttodoitem-create-方法我看到它在这个 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?所以,我在我自己的 controller 中做了一些测试,我看到当我从浏览器发送请求时,服务器端总是创建一个新的工作线程来处理请求,所以我有疑问:如果 controller 已经在不同的线程中处理请求,为什么我还要使用 async/await? Since the request being handled in a new thread, I don't think it will block any other request.由于请求是在新线程中处理的,我认为它不会阻止任何其他请求。

The async and await pattern is about scalability.异步和等待模式是关于可伸缩性的。 Why block a thread when you can use an IO completion port?当您可以使用 IO 完成端口时,为什么要阻塞线程? 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.异步和等待模式卸载工作(术语使用松散)并允许线程池潜在地恢复线程并在其他地方使用它,直到您的IO 工作完成。

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.您现在可能没有注意到差异,但是当您开始将网站扩展到 1000 个并发作业时,有效地使用资源将开始变得很重要。 One of those tools you can use, is... the async and await pattern .您可以使用的工具之一是... async 和 await 模式

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:)如果不写一篇关于语言特性的内部工作原理及其用途的论文,它可能是您开始研究 async 和 await 模式以回答您自己的一些最常见问题的好地方,您将获得乐趣并获得收益成就感:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM