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();
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With