Question

I have a pretty simple controller:

  public class HomeController : Controller
    {
        public ActionResult Index()
        {
            Session["SomeData"] = "123";
            return View();
        }

        [HttpPost]
        public ActionResult LongTest()
        {
            Thread.Sleep(5000);
            return Json(new { Text = DateTime.Now.ToString("hh:mm:ss.fff") + " - LongTest"});
        }

        [HttpPost]
        public ActionResult CantAnswer()
        {
            return Json(new { Text = DateTime.Now.ToString("hh:mm:ss.fff") + " - CantAnswer"});
        }
    }

I use these methods from the client's side this way:

<script type="text/javascript">
    $(document).ready(function () {
        $('#btnLongOperation').click(function () {
            $.post("/Home/LongTest", null, function (data) {
                $('#result').text(data.Text);
            }, "json");
        });

        $('#btnWnotWork').click(function () {
            $.post("/Home/CantAnswer", null, function (data) {
                $('#result').text(data.Text);
            }, "json");
        });
    });
</script>
<div>
    <input id="btnLongOperation" type="button" value="Long operation"/>
    <input id="btnWnotWork" type="button" value="Won't work"/>
</div>
<div id="result">

If I click the first button and then without waiting for 5 seconds click the second button my second action won't be called. If you remove the string with using session in the Init method you will see that the actions are able to be called without waiting for each other. However, once you use session object you will not see a result of second action untill the first one is finished. Can anyone explain this behavior of asp.net mvc?

Was it helpful?

Solution

This is caused by session locking. In essence, each request that uses session state places a lock on it until it is done reading. Subsequent requests cannot access Session until the previous request releases the lock.

The purpose of this is to ensure the integrity of session data. For example, what would happen if the request A needed to write to the session and request B needed to read, but the requests were issued simultaneously? The data that B reads is unpredictable as you have no way of knowing whether it will be pre or post-write.

Read here for more information:

http://www.timvasil.com/blog14/post/2008/04/16/Handling-multiple-simultaneous-requests-from-a-user-in-ASPNET.aspx

OTHER TIPS

You can use asynchronous controllers for different behaviour. See this link

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top