
I am working on a standard ASP.NET MVC project that uses Ajax, a lot. After a page loads, multiple ajax calls were fired up to a single method in a single controller(which is bad by design itself). I noticed a few really weird issues:
- Although the AJAX call was made in parallel, execution of second call was made only after the completion of first request.
- The whole page went unresponsive since the completion of all those requests took couple of minutes.
Nothing got into my head at the time and I started googling for the reason behind this weird behaviour.
After googling for an hour or two, I found this article by John Culviner and reason behind the same.
Reason
Reason behind the behavior is ASP.NET session state. As the MSDN documentation states
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. (The second session can also get access if the exclusive lock on the information is freed because the first request exceeds the lock time-out.) If the EnableSessionState value in the @ Page directive is set to ReadOnly, a request for the read-only session information does not result in an exclusive lock on the session data. However, read-only requests for session data might still have to wait for a lock set by a read-write request for session data to clear.
In the project I am working on, an endpoint was called concurrently and switch case was written in Action method which delegated the task to respective functions. So, I broke it down to separate endpoints inside the controller and set the session mode as readonly
[SessionState(SessionStateBehavior.ReadOnly)]
public class ABCController : Controller
{
// action methods go here
}
Reference Articles:
- https://josef.codes/c-sharp-mvc-concurrent-ajax-calls-blocks-server/
- http://johnculviner.com/asp-net-concurrent-ajax-requests-and-session-state-blocking/?ref=josef-ottosson
- https://learn.microsoft.com/en-us/previous-versions/ms178581(v=vs.140)
Thanks for reading !!