IRequiresSessionState vs IReadOnlySessionState

Oleg Grishko picture Oleg Grishko · Nov 7, 2011 · Viewed 8.1k times · Source

What is the difference between IRequiresSessionState and IReadOnlySessionState beside the inability of the second to save changes to the session variables?

Both provide me the ability to access session variables in my HttpHandler. But why would I prefer IReadOnlySessionState? It just restricts me from saving the session for the next request.
Or does it gives me an performance advantage over IRequiresSessionState?

When would I prefer to use IReadOnlySessionState over IRequiresSessionState?

Answer

Chris picture Chris · Sep 20, 2012

One critical difference is that IRequiresSessionState puts an exclusive lock on the current session, thereby potentially limiting the # of concurrent requests from the current user. (For more background on this locking phenomenon, see Is it possible to force request concurrency when using ASP.NET sessions?)

In contrast, IReadOnlySessionState does not acquire an exclusive lock.

This is the same thing documented in renad's helpful answer to an almost identical SO question.

The best official documentation I've found for this is from MSDN article Session State Providers:

Three of the most important methods in a session state provider are GetItem, GetItemExclusive, and SetAndReleaseItemExclusive. The first two are called by SessionStateModule to retrieve a session from the data source. If the requested page implements the IRequiresSessionState interface (by default, all pages implement IRequiresSessionState), SessionStateModule's AcquireRequestState event handler calls the session state provider's GetItemExclusive method. The word "Exclusive" in the method name means that the session should be retrieved only if it's not currently being used by another request. If, on the other hand, the requested page implements the IReadOnlySessionState interface (the most common way to achieve this is to include an EnableSessionState="ReadOnly" attribute in the page's @ Page directive), SessionStateModule calls the provider's GetItem method. No exclusivity is required here, because overlapping read accesses are permitted by SessionStateModule.

Note the parallel between explicitly using these interfaces and using the EnableSessionState Page directive:

  • EnableSessionState=False <-> no I*SessionState interface
  • EnableSessionState=True <-> IRequiresSessionState interface
  • EnableSessionState=ReadOnly <-> IReadOnlySessionState