gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 12:11:07 25 4
gpt4 key购买 nike

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

在项目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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com