Task.Run without async or await

对着背影说爱祢 提交于 2019-12-12 05:00:01

问题


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(() =>
        {
            ....
        }
}

回答1:


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.



来源:https://stackoverflow.com/questions/31321046/task-run-without-async-or-await

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!