c# - 为什么是 "Using asynchronous [...] methods on CPU-bound [providing] no benefits and results in more overhead."

标签 c# asp.net-mvc multithreading asynchronous async-await

我遇到了这个article .在“选择同步或异步操作方法”下,作者声明在以下情况下不应使用异步操作方法:

The operations are primarily CPU operations instead of operations that involve extensive disk or network overhead. Using asynchronous action methods on CPU-bound operations provides no benefits and results in more overhead.

我不明白为什么会这样。因为如果我有一个计算斐波那契数的方法需要 30 秒的计算,那么调用主要是 CPU 绑定(bind)。不进行此异步操作会阻塞调用线程 30 秒,并使应用程序无响应。

你能帮我推理一下吗?

最佳答案

Not making this async would block the calling thread for 30 seconds and make the application unresponsive.

你在混淆Concurrency and Parallelism .作者正在谈论使用 async-await 来利用 IO bound 操作,您可以在线程执行 IO 工作(例如网络或数据库)时免费调用线程调用,而不是同步阻塞它们直到该操作完成。

您所说的是在后台线程上执行 CPU 绑定(bind) 工作。在 ASP.NET 的上下文中,您正在线程池分配的专用线程上执行工作。仅仅为了完成 CPU 密集型工作而启动一个新线程是没有用的。为此,您可以简单地在当前正在执行的线程上执行。

此外,在 ASP.NET 中使用 Task.Run 被认为是危险的。您应该只卸载在运行时环境中注册其工作的对象,例如 BackgroundTaskManager .

如果这是一个 UI 应用程序并且您有一个 CPU 绑定(bind)操作,那么将工作推迟到后台线程将是一个有效的做法,使用 Task.Run

关于c# - 为什么是 "Using asynchronous [...] methods on CPU-bound [providing] no benefits and results in more overhead.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31246635/

相关文章:

Android:对于 Canvas 动画,最好有 1 个大线程,或多个小线程

c# - 查询数据表字段包含列表中任意项的行<string>

javascript - MVC Razor 中的 DropBox

Java Swing 线程问题

c# - 在 Json API 调用中卡住了 DateTime 对象名称

c# - 多个页面的单个 Controller

java - 新线程导致 ContextNotActiveException

c# - 如何使用元刷新强制缓存图像?

c# - UnityContainer.BuildUp() - 仅当属性为空时,我可以让它将新实例注入(inject)到属性中吗?

c# - 如何从 MVC3 中的编辑页面更新 View 模型?