I am investigating async
and await
in the context of ASP.NET MVC controller methods, and am getting some unexpected behavior.
I have the following controller class:
[SessionState(System.Web.SessionState.SessionStateBehavior.Required)]
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
public async Task<ActionResult> Check1()
{
Session["Test"] = "Check";
System.Diagnostics.Debug.WriteLine("Session: " + Session["Test"]);
await Task.Delay(20000);
return View();
}
public ActionResult Check2()
{
var test = Session["Test"];
ViewBag.Test = test;
return View();
}
}
And simple views for each method Check1 and Check2:
Check1
@{
ViewBag.Title = "Check1";
}
<h2>View with Delay</h2>
Check2
@{
ViewBag.Title = "Check2";
var check = ViewBag.Test;
}
<h2>Immediate View @check</h2>
Now immediately after starting the application, when I open http://localhost:23131/Home/Check1
in one tab and http://localhost:23131/Home/Check2
in 2nd tab, the call to Check1
returns after 20 seconds as expected, and call to Check2
returns immediately, but it doesn't have the value set in the session state, which I fail to understand why. It should be set immediately since it is before the delay. However, correct value is printed on output window.
Now after Check1 returns, hitting refresh on Check2
tab brings value from session in viewbag
and displays it.
After this, if I again refresh both tabs, Check2
doesn't return after Check1 is completed (20 seconds delay) despite Check2 being async
.
My questions are:
- First time when both tabs are opened,
Check2
returns immediately due toCheck1
beingasync
, and it is not blocked despiteSessionStateBehavior.Required
sinceawait
statement returns control until awaited task completes. Why doesn'tCheck2
gets the value beforeCheck1
returns? - After 1st time,
Check2
gets stuck untilCheck1
returns despiteCheck1
beingasync
, why is this? Upon re-running the application,Check1
returns immediately as stated in the previous question but only once. - Is there any concept I have missed or stated wrong in my explanation.
Using ASP.NET with .NET Framework 4.5, Visual Studio 2013 running on Windows 7 Ultimate.