Task.Run 没有异步或等待 [英] Task.Run without async or await
问题描述
如果我将一些我正在调用的方法从我的控制器放到 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:
- 您正在使用线程池中的四个线程来执行此操作.如果这个动作是在重负荷下——即.它经常被调用 - 池中可用线程的数量可能成为新的瓶颈.
- 函数 1 和函数 2 的运行时间基本上是无限的,因为没有客户端会等待它们.如果向这些函数添加了过多的逻辑,您可能会再次耗尽池中的线程.
- 正如@LasseVKarlsen 提到的,这可能会导致死锁一>.
- 如果这些是受 CPU 限制的函数,那么并行执行它们可能不会给您带来任何好处.(但是,不等待一和二可能会购买客户端很多.)如果下面有 I/O 操作(例如网络调用、数据库调用、文件系统调用),您可能需要查看进入 在 ASP.NET MVC 中使用异步控制器 代替.
- 正如@StephenCleary 所指出的,ASP.NET 不会跟踪您的线程.如果发生回收(例如当您编辑 web.config 时),它将始终作为请求的一部分完成功能三,但第一和第二可能会被取消.
- 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屋!