Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the lock-free sessions in C#?

I know about the sessions in C# and how to define them as well. But today I heard a term Lock-free sessions. I googled it but did not get any answer exactly matching to my question. Can anyone please explain something about lock-free sessions in C# and how to write a code for them?

like image 585
asma Avatar asked Oct 23 '25 21:10

asma


1 Answers

Here is some content from msdn section Concurrent Request and Session State

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.

so whenever the concurrent request comes with the same sessionId it just enters in exclusive lock. To create lock free session you just need to set EnableSessionState to ReadOnly as per above documentation from MSDN. And this is called lock-free session.

Note: when you specify EnableSessionState as ReadOnly. asp.net would not acquire any exclusive lock on session and eventually it also makes session as readonly for that page.

Here is very good discussion about the session locks in asp.net on another Stack overflow thread:- link

like image 138
Jenish Rabadiya Avatar answered Oct 26 '25 10:10

Jenish Rabadiya