Async, Task.Delay and HtmlHelper MVC 4

Strange problem

Not sure what happens to the thread after running Task.Delay in the test class. when it is called from the Htmlhelper static class, I do not get any result, when I debug it after Task.Delay has executed the thread, it does not fall into the return statement. it was developed in asp.mvc 4

Code view

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

Html helper

    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>";
        }
    }

Asynchronous operation

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;
    }
}

The same code (test class) works fine if the call is made from the 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();
    }
}
+4
source share
1 answer

You see the deadlock problem that I am describing on my blog.

; ASP.NET MVC , . , , , .

+8

Source: https://habr.com/ru/post/1530439/


All Articles