gpt4 book ai didi

multithreading - 异步、Task.Delay 和 HtmlHelper MVC 4

转载 作者:行者123 更新时间:2023-12-03 22:41:18 25 4
gpt4 key购买 nike

奇怪的问题

不确定在测试类中执行 Task.Delay 后线程会发生什么。当它从静态 Htmlhelper 类调用时,我没有得到任何结果,当我在 Task.Delay 执行后调试它时,线程没有命中 return 语句。这是在asp.mvc 4中开发的

查看代码

 <div>
@Html.Method1().Result.ToString();
</div>

Html 助手
    public static class SomeHtmlHelper
{
public static async Task<string> Method1(
this HtmlHelper htmlHelper)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
var testObj = new test();
var a = testObj.Service1Async();
var b = testObj.Service2Async();
await Task.WhenAll(a,b);
stopwatch.Stop();
return "<div>"+stopwatch.Elapsed.ToString()+"</div>";
}
}

异步工作
public class test
{

public async Task<int> Service2Async()
{
await Task.Delay(2000);
return 10;
}

public async Task<int> Service1Async()
{
await Task.Delay(2000);
return 10;
}
}

如果调用来自 Controller ,则相同的代码(测试类)工作正常
public class HomeController : Controller
{
public async Task<ActionResult> About()
{
ViewBag.Message = "Your app description page.";
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
var testObj = new test();
var a = testObj.Service1Async();
var b = testObj.Service2Async();
await Task.WhenAll(a, b);
stopwatch.Stop();
var millisec = stopwatch.Elapsed.ToString();
return View();
}
}

最佳答案

您看到的是 deadlock issue我在我的博客上描述的。

从 View 中调用任何异步代码是一个坏主意; ASP.NET MVC 对那个阶段可以调用的内容非常敏感。最好在 Controller 中完成所有异步工作,然后将包含结果的模型传递给 View 。

关于multithreading - 异步、Task.Delay 和 HtmlHelper MVC 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22228664/

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