Task.Run 没有异步或等待 [英] Task.Run without async or await

查看:56
本文介绍了Task.Run 没有异步或等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我将一些我正在调用的方法从我的控制器放到 Task.Run 中,这到底是在做什么?我没有使用异步函数,也没有使用 await.

If I put a few of the methods I'm calling, from my controller, into Task.Run what exactly is this doing? I'm not using an async function and I'm not using await.

...
FunctionOne();
FunctionTwo();
return View(FunctionThree().Result);
}

private void FunctionOne()
{
        Task.Run(() =>
        {
            ....
        }
}

private void FunctionTwo()
{
        Task.Run(() =>
        {
            ....
        }
}

private Task<MyType> FunctionThree()
{
        return Task.Run(() =>
        {
            ....
        }
}

推荐答案

正如@LasseVKarlsen 解释的那样,此代码尝试并行执行函数一、二和三.Task.Run 立即将线程池上的指定工作排队,.Result 将阻塞调用线程,直到它的 任务(只有它的任务)已完成.

As @LasseVKarlsen explains, this code attempts to execute functions One, Two and Three in parallel. Task.Run immediately queues the specified work on the thread pool, and .Result will block the calling thread until its Task (and only its task) is complete.

这可能是也可能不是一个好的设计.需要考虑的一些事项:

This may or may not be a good design. Some things to consider:

  • You're using four threads from your thread pool to execute this action. If this action is under heavy load -- ie. it's called often -- the number of available threads in your pool could become a new bottleneck.
  • Functions One and Two have an essentially unbounded runtime since no client will be waiting on them. If too much logic is added to those functions, you could again run out of threads in your pool.
  • As @LasseVKarlsen mentions, this may lead to a deadlock.
  • If these are CPU-bound functions, then doing them in parallel may not buy you anything. (However, not waiting on One and Two might buy the client a lot.) If there are I/O operations underneath (eg. network calls, database calls, filesystem calls), you may want to look into Using an Asynchronous Controller in ASP.NET MVC instead.
  • As @StephenCleary notes, ASP.NET doesn't keep track of your threads. If a recycle occurs (say when you edit your web.config), it will always finish function Three as part of the request, but One and Two may be cancelled.

这些考虑是否表明您的设计发生变化取决于每个功能的作用、它们需要多长时间以及它们对您的业务逻辑的重要性.

Whether these considerations suggest a change in your design is a question of what each function does, how long they take, and how important they are to your business logic.

这篇关于Task.Run 没有异步或等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆