Concurrent Sessions in MVC2

September 21st, 2010 by David Bending Leave a reply »

There’s lots of rules that control how many concurrent connections you can have in an ASP.net MVC2 application.

Firstly the browser itself limits the number of connections it will make to the same domain.  The limit used to be 2 (as per the HTTP specification).  Some browsers increase this limit, but older browsers like IE6 will still stick to it.

Secondly you have the number of threads available in IIS to content with.  Thomas Masquardt’s Blog gives a very detailed explanation of this.

Finally MVC itself has some limitations. Basically you can only have a single request using a read-write session at any given time.  This means that if you have a controller serving up images, and you don’t take any steps to avoid the problem, you will only ever serve up one image at a time.  Imran Baloch’s Blog gives a lot more information about this and shows how to create session-less actions to avoid the issue.  For me the solution is quite simple.  By placing the following code in Global.asax.cs:

protected void Application_BeginRequest()
{
    if((Request.Url.AbsoluteUri.ToUpperInvariant().Contains("REFRESHPRICES")
        && Request.Cookies["ASP.NET_SessionId"] != null))
    {
        Context.SetSessionStateBehavior(SessionStateBehavior.ReadOnly);
    }
}

I can make the session for my action read-only, and sidestep the limit.

Warning

Just marking the session sate as read-only doesn’t prevent you from trying to modify the session.  It’s up to you to maintain thread-safety if you decide to lie to the framework.

Share
Advertisement
Celtic-Style Contemporary Jewellery and Gifts

Leave a Reply