What are the lock-free sessions in C#?

和自甴很熟 提交于 2021-02-07 23:15:31

问题


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?


回答1:


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




回答2:


The session state module implements a readers – writers locking mechanism and queues the access to session state values. A page that has session-state write access will hold a writer lock on the session until the request finishes. A page gains write access to the session state by setting the EnableSessionState attribute on the @Page directive to True. A page that has session-state read access — for example, when the EnableSessionState attribute is set to ReadOnly — will hold a reader lock on the session until the request finishes.



来源:https://stackoverflow.com/questions/27957295/what-are-the-lock-free-sessions-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!