February 10, 2014

ASP.NET Session and concurrent access

Problem

In one of my projects I found some a strange at first sight issue related to concurrent Session usages. During one long request the other parallel requests were waiting until the previous one is finished.
This issue occurs when user tries to download file from ashx-handler. Handler requires Session to get some user-related configuration which is stored there.

Overview

I've tried to dig deeper and that what I've found.
By default no concurrent access to the asp.net session state is allowed. Requests with same SessionID will be locked exclusively to prevent potential corruption of its state.

What does it mean:

When you have request1 `in progress` and trying to do request2 - Session object will be locked by request1 and our code in request2 will be waiting for request1 completed.

ASP.NET Session is thread safe and synchronization mechanism is based on System.Threading.ReaderWriterLock.