C#中的无锁会话是什么?

What are the lock-free sessions in C#?

我知道 C# 中的会话以及如何定义它们。但是今天我听到了一个术语Lock-free sessions。我用谷歌搜索但没有得到与我的问题完全匹配的答案。谁能解释一下 C# 中的无锁会话以及如何为它们编写代码?

会话状态模块实现readers – writers locking mechanism并对访问进行排队到会话状态值。具有会话状态写访问权限的页面将持有会话上的写入器锁,直到请求完成。通过将 @Page 指令上的 EnableSessionState 属性设置为 True,页面可以获得对会话状态的写访问权。具有会话状态读取访问权限的页面 — 例如,当 EnableSessionState 属性设置为 ReadOnly 时 — 将在会话上保持 reader 锁定,直到请求完成。

这是 msdn 部分 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.

因此,只要并发请求带有相同的 sessionId,它就会进入独占锁。要创建无锁会话,您只需按照上述 MSDN 文档将 EnableSessionState 设置为 ReadOnly。这就是所谓的无锁会话.

注意:当您将 EnableSessionState 指定为 ReadOnly 时。 asp.net 不会在会话上获得任何独占锁,最终它还会使会话对该页面只读。

asp.net 另一个 Stack 溢出线程中关于会话锁的讨论非常好:- link