The other day I learned something interesting about the inner workings of ASP .Nets session state management. One of the nice features it provides is automatically making usage of the session state thread safe between the various threads which may be handling requests from the same user (with the same sessionId).
Apparently the way it goes about doing this is by locking the session state object for a user for the lifetime of any handler that requires the session state (anything that implements IRequiresSessionState). Normally this is a handy feature making it so that developers don’t have to worry about the thread safety issues that would normally come with sharing the same objects between threads. However in some instances this can lead some some unexpected behavior if you’re not aware of this.
So the other day I was implementing an asynchronous HTTP handler in which I needed to access a user’s session state. To do this you simply make the handler class inherit from IRequiresSessionState. However in doing so the users session state becomes locked for the duration of the Async request (in this particular case it could be several minutes before the response was sent). This caused any subsequent requests which required the session state to hang while they waited for the lock to be released.
So after all of this I can say I learned something interesting and have added a new best practice to my repertoire; don’t use the session state within long running handlers!