c# - 为什么将 .Wait() 添加到我的任务有时会允许任务使用主线程?

标签 c# task task-parallel-library threadpool

我试图了解异步是如何工作的,但有一种情况我已最大限度地简化,但我找不到任何解释。

在项目 mvc asp.net Framework 4.6 上:

...
public class Test {
    public static void Work(int id) {

        if (id == Thread.CurrentThread.ManagedThreadId) {
            Debug.WriteLine("******************************");
            Debug.WriteLine("***     BOOOMMMM !!!!!!!   ***");
            Debug.WriteLine("******************************");
        }
    }
}

public class HomeController : Controller {
    public ActionResult Index() {
        var id = Thread.CurrentThread.ManagedThreadId;
        Task.Run(() => { Test.Work(id); });

        return View();
    }
...

当我执行上面的代码时:

if (id == Thread.CurrentThread.ManagedThreadId)

从未得到验证。 DoWork() 在主线程之外的另一个线程上运行。对我来说,这很正常,这就是我在阅读过程中一直理解的。

但是如果我在 Task.Run 上等待

Task.Run(() => { Test.Work(id); }).Wait();

有时它是主线程之外的另一个线程,有时不是,我不明白。

Here文中写道:

Task.Run starts a task on the thread pool to do the calculations. The ASP.NET thread pool has to deal with (unexpectedly) losing one of its threads for the duration of this request.

好吧,在他的示例中没有 Wait(),但这有什么区别,无论如何,Wait() 是在 Work() 之后调用的,所以无论是否有 Wait(),Work() 都应该具有相同的行为.

如果有人能给我解释,我将不胜感激。

最佳答案

当您等待时,TPL 可以将任务内联到当前线程中。如果任务尚未在另一个线程上启动,则可能会发生这种情况。这是一种性能优化。

It is a very controversial feature that injects subtle bugs into applications.本质上,对任务的任何等待都可以不确定地运行任意代码。

关于c# - 为什么将 .Wait() 添加到我的任务有时会允许任务使用主线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52258698/

相关文章:

c# - 负责 MVVM 中的异步执行

c# - 如何从我的应用程序打开网页?

c# - 任务结果事件完成

c# - 实现 IEqualityComparer<T> 以比较任何类(包括匿名类)的任意属性

django - 使用 django 和 celery 运行周期性任务

Hadoop任务分配

C# 任务返回输出

c# - 理想的任务数量

c# - MSChart滚动条实现+绘图

c# - 将参数传递给 SharePoint 计时器作业