使所有控制器方法异步简单的方法

Make all conroller methods async easy way

我有一个网络 api,其控制器方法如下:

public HttpResponseMessage DoSmth() {
    doingSmth();
}

我在此处阅读了有关服务器线程的信息: 在这里:https://docs.microsoft.com/en-us/archive/msdn-magazine/2014/october/async-programming-introduction-to-async-await-on-asp-net#synchronous-vs-asynchronous-request-handling

business\data 访问层的实现是同步的(并且 庞大 ),没有时间将所有内容重构为 async task<>。 有没有什么方法可以只重构控制器,即“最顶层”的方法变成异步的,这样服务器就不会 运行 没有线程了?

Is there some way to refactor only the controller, i.e. "topmost" methods into being asyncronous so server won't run out of threads?

没有

你可以这样想:同步调用会阻塞一个线程。只要您的业务逻辑/DAL 方法是同步的,它们就会阻塞一个线程。

正如一些人在评论中指出的那样,Task.Run 将允许这些方法阻塞线程池线程而不是调用线程,这对于许多 GUI 应用程序来说是一个很好的方法(阻塞线程池线程而不是GUI 线程),但它在服务器应用程序上会适得其反(阻塞一个线程池线程而不是另一个线程池线程)。

我建议首先分析您的应用并确定哪些请求最慢或最常被调用,然后仅将那些更改为 async。在创建同步方法的异步等价物时,您可以使用 flag argument hack(归因于我)来避免 logic/DAL 类型中的代码重复。