c# - 您可以通过在 Controller 中对同步代码使用 Task.Run 来提高吞吐量吗?

标签 c# asp.net-mvc task

在我的 Controller 中,我需要调用方法 BlockingHttpRequest() 来发出 http 请求。运行速度比较慢,会阻塞线程。
我无法重构该方法以使其异步。

将此方法包装在 Task.Run 中以至少释放 UI/ Controller 线程是否更好?
我不确定这是否真的改善了什么,或者只是做了更多的工作。

public class MyController : Controller
{
    public async Task<PartialViewResult> Sync()
    {
        BlockingHttpRequest();
        return PartialView();
    }

    public async Task<PartialViewResult> Async()
    {
        await Task.Run(() => BlockingHttpRequest());
        return PartialView();
    }
}

在实践中,我有几个这样的情况,其中 BlockingHttpRequest() 分别需要 500 毫秒和 5000 毫秒。


我知道 Task.Run() 不会让我的函数更快返回。

我认为增加吞吐量可能会有一些好处。通过释放 Controller 的线程,其他用户可以使用它吗?这意味着在 MVC 中 Controller 线程和后台工作线程之间存在差异。

最佳答案

By freeing up the controller's thread, does that make it available to other users?

是的,确实如此。

This would imply that in MVC there is a difference between controller threads and background worker threads.

不,没有。因为正如您正在释放一个现在可以为其他请求提供服务的线程池线程一样,您也在使用一个现在不能为其他请求提供服务的新线程池线程。因此能够处理其他请求的线程总数是相同的。

I thought that there might be some benefit of increased throughput.

没有。您正在浪费一些时间在线程之间进行上下文切换、等待安排新工作人员以及与您正在做的工作相关的其他开销,而您却得不到任何返回。

关于c# - 您可以通过在 Controller 中对同步代码使用 Task.Run 来提高吞吐量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40738634/

相关文章:

c# - 如何在 C# 的表单应用程序中输出参数?

asp.net-mvc - 将 Ajax.BeginForm 与 A​​SP.NET MVC 3 Razor 结合使用

asp.net - 注册外部登录时 CreateUserAsync 失败

c# - 任务的延续(由 async/await 构建)在 WPF 应用程序的主线程上运行,但在控制台应用程序的子线程上运行

c# - 在键入挂起时设置 UITextField 的文本然后使应用程序崩溃

c# - 处理大型位图(最大 3GB)

c# - C# SSH .Net 库中的 Sudo 命令

javascript - 在 jQuery 中访问 Html 编码的字段值

django - 使用 Django 启动和停止定期后台任务

ios - 使用 dataTask 在 func 上快速显示和隐藏事件指示器