Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async, Task.Delay and HtmlHelper MVC 4

Strange issue

Not sure what happens to the thread after executing the Task.Delay in the test class. when it is called from the static Htmlhelper class, i am not getting any result, when i debug it after the Task.Delay executed the thread is not hitting the return statement. this developed in asp.mvc 4

View Code

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

Async work

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 from 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();
    }
}
like image 310
sudhakar kutti Avatar asked Feb 13 '23 14:02

sudhakar kutti


1 Answers

You're seeing a deadlock issue that I describe on my blog.

It's a bad idea to call any asynchronous code from the view; ASP.NET MVC is pretty sensitive about what can be called at that stage. It's better to do all asynchronous work in the controller and then pass the model containing the results to the view.

like image 87
Stephen Cleary Avatar answered May 10 '23 03:05

Stephen Cleary