75

A few days back I asked this question:

Why does $.getJSON() block the browser?

I fire six jQuery async ajax requests at the same controller action pretty much all at once. Each request takes 10 seconds to return.

Through debugging and logging requests to the action method I notice that the requests are serialised and never run in parallel. i.e. I see a timeline in my log4net logs like this:

2010-12-13 13:25:06,633 [11164] INFO   - Got:1156
2010-12-13 13:25:16,634 [11164] INFO   - Returning:1156
2010-12-13 13:25:16,770 [7124] INFO   - Got:1426
2010-12-13 13:25:26,772 [7124] INFO   - Returning:1426
2010-12-13 13:25:26,925 [11164] INFO   - Got:1912
2010-12-13 13:25:36,926 [11164] INFO   - Returning:1912
2010-12-13 13:25:37,096 [9812] INFO   - Got:1913
2010-12-13 13:25:47,098 [9812] INFO   - Returning:1913
2010-12-13 13:25:47,283 [7124] INFO   - Got:2002
2010-12-13 13:25:57,285 [7124] INFO   - Returning:2002
2010-12-13 13:25:57,424 [11164] INFO   - Got:1308
2010-12-13 13:26:07,425 [11164] INFO   - Returning:1308

Looking at the network timeline in FireFox I see this:

alt text

Both the log sample above and the Firefox network timeline are for the same set of requests.

Are requests to the same action from the same page serialised? I'm aware of serialised access to the Session object in the same session, but no session data is being touched.

I stripped the client side code down to a single request (the longest running one) but this still blocks the browser, i.e. only when the ajax request completes does the browser respond to any link clicking.

What I also observe here (in Chrome's developer tools) is that upon clicking on a link when a long running ajax request is executing it reports a Failed to load resource error immediately which suggests that the browser has killed (or is attempting to kill and waiting?) the ajax request:

alt text

However the browser still takes an age to redirect to the new page.

Are ajax requests really asynchronous or is this sleight of hand because javascript is actually single threaded?

Are my requests just taking too long for this to work?

The problem occurs in Firefox and IE as well.

I also changed the script to use $.ajax directly and explicitly set async: true.

I'm running this on IIS7.5, both the Windows 2008R2 and Windows 7 flavours do the same thing.

Debug and release builds also behave the same.

18
  • Did you test this in firefox/IE. Maybe its a chrome issue? Commented Dec 13, 2010 at 11:43
  • @aseem - it's the same in F/Fox and IE Commented Dec 13, 2010 at 11:45
  • Maybe your script changes the async setting somewhere else. Commented Dec 13, 2010 at 11:54
  • Can you check in FF/Firebug when the multiple requests are send(Net Panel in firebug). Those timelogs does not seem right, jquery ajax requests are async for sure and must run in parallel. Commented Dec 13, 2010 at 11:56
  • 1
    @aseem - there are no "sent" times in the request headers. What I'm saying is that because they all get requested at once firefox (or google) can't sort by any sensible order. The order that is there is due to the time taken for each underlying XHR to respond and acknowledge that "yes indeed I have sent this request" so there may be a few milliseconds of difference between each one due to differences in making a TCP/IP connection. Hence the out of order timeline. However I know for a fact these calls are serialised (the logging in the controller action tells me this).....cont... Commented Dec 13, 2010 at 13:17

2 Answers 2

91

The answer was staring me in the face.

ASP.NET Session State Overview:

Access to ASP.NET session state is exclusive per session, which means that if two different users make concurrent requests, access to each separate session is granted concurrently. However, if two concurrent requests are made for the same session (by using the same SessionID value), the first request gets exclusive access to the session information. The second request executes only after the first request is finished.

Annoyingly I'd skimmed paragraph this a couple of weeks ago not really taking in the full impact of the bold sentences. I had read that simply as "access to session state is serialised" and not "all requests, no matter whether you touch session state or not, are serialised" if the requests came from the same session.

Fortunately there is a work around in ASP.NET MVC3 and its possible to create session-less controllers. Scott Guthrie talks about these here:

Announcing ASP.NET MVC 3 (Release Candidate 2)

I installed MVC3 RC2 and upgraded the project. Decorating the controller in question with [SessionState(SessionStateBehavior.Disabled)] solves the problem.

And of course typically I just found this in Stack Overflow a few minutes ago:

Asynchronous Controller is blocking requests in ASP.NET MVC through jQuery

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the help with a tough bug! Is it just me or is this glaringly stupid default behavior?
Note that using [SessionState(SessionStateBehavior.Disabled)] may open security breach into your application, for instance access to private data in multiple simultaneous request, with this option you have no way to know is an user is logged, nor if a session is active, etc... If you need to access to the session you can use [SessionState(SessionStateBehavior.ReadOnly)], so you have still access to your session, though you can't edit it, but still may help in many cases.
@GregoireD. - Thanks for the info about SessionStateBehavior.ReadOnly. I've a feeling I looked at that and that it still causes serialised access to your Session. The app uses Forms Authentication plus a cookie/db lookup combo to lock down access to that controller. The data returned from the controller itself isn't confidential, but we did take measures to prevent people fiddling out of idle curiosity.
SessionStateBehaviour.ReadOnly seems to be working in my case, and still allows access to the Session.
9

I was trying to reproduce this but was unable. Here's my test:

private static readonly Random _random = new Random();

public ActionResult Ajax()
{
    var startTime = DateTime.Now;
    Thread.Sleep(_random.Next(5000, 10000));
    return Json(new { 
        startTime = startTime.ToString("HH:mm:ss fff"),
        endTime = DateTime.Now.ToString("HH:mm:ss fff") 
    }, JsonRequestBehavior.AllowGet);
}

And the call:

<script type="text/javascript" src="/scripts/jquery-1.4.1.js"></script>
<script type="text/javascript">
    $(function () {
        for (var i = 0; i < 6; i++) {
            $.getJSON('/home/ajax', function (result) {
                $('#result').append($('<div/>').html(
                    result.startTime + ' | ' + result.endTime
                ));
            });
        }
    });
</script>

<div id="result"></div>

And the results:

13:37:00 603 | 13:37:05 969
13:37:00 603 | 13:37:06 640
13:37:00 571 | 13:37:07 591
13:37:00 603 | 13:37:08 730
13:37:00 603 | 13:37:10 025
13:37:00 603 | 13:37:10 166

And the FireBug console:

alt text

As you can see the AJAX action is hit in parallel.


UPDATE:

It seems that in my initial tests the requests are indeed queued in FireFox 3.6.12 and Chrome 8.0.552.215 when using $.getJSON(). It works fine in IE8. My tests were performed with a ASP.NET MVC 2 project, VS2010, Cassini web server, Windows 7 x64 bit.

Now if I replace $.getJSON() with $.get() it works fine under all browsers. That leads me to believe that there is something with this $.getJSON() which might cause the requests to queue. Maybe someone more familiar with the internals of the jQuery framework would be able to shed more light on this matter.


UPDATE 2:

Try setting cache: false:

$.ajax({
    url: '/home/ajax', 
    cache: false,
    success: function (result) {
        $('#result').append($('<div/>').html(
            result.startTime + ' | ' + result.endTime
        ));
    }
});

12 Comments

@Kev, yes it's a bit strange. Could you try replacing $.getJSON() by $.get()? I tested this with Cassini. I don't have IIS installed and cannot verify.
@darin - I tried $.getJSON() and went straight to $.ajax() and the results are the same.
Running this sample in IE8 works fine for me. However in FF and Chrome the requests are not sent in parallel. I´m using cassini and VS2010.
@uvita, does replacing $.getJSON() with $.get() make any difference? For me it makes a difference. When using $.getJSON the requests seem to be queued.
@darin, no it didn´t. Exactly the same results in every browser.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.