Concurrency in ASP.NET Sessions

Last week some of the guys on my team were running some tests in our application and they noticed a contention problem. When a large report was running any other requests hung until the report was done being generated.

There were no transactions locking the database and no locks on the code either. After testing for a while I noticed that when I used 2 different browsers the problem would happen. Ha! So it must have something to do with the Session. The answer was on the bottom of the Session State documentation page on MSDN. Here is the section that matters:

"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."

 So the problem only happens if you have multiple request from the same session. Still this is very annoying! This is done so that the Session maintains the consistency. If you don't need to write to the session (only read) the session state may be defined as ReadOnly in which case there will be no locking.

Depending on your application you might want to set the sessionState as ReadOnly in the web.config (affects all pages) and then mark each page that needs write access to use sessionState=true. Or you may want to do it the other way around. Set the pages that take a long time to process as sessionState=ReadOnly (so they don't block) and leave all the other pages that process quickly as they are.

 To set up the web.config:

<system.web>
    <pages enableSessionState="ReadOnly"/>
</system.web>

To set up a single page use the Page directive:

<%@ Page ... EnableSessionState="True" %>

Setting the Page directive will override the web.config setting.

Hope this helps.

Comments

Leave your comment

Author

Email (never displayed)

Website

Comment  
HTML is NOT allowed. Use regular line breaks and those will be respected.