I believe that reading from Session
is always a CPU-only operating. Loading the session state happens as some early point in the pipeline. The loading step would indeed benefit from being asynchronous. Reading from the dictionary should stay as it always has been.
Unfortunately, the SessionStateStoreProviderBase
class only has synchronous methods. Deriving from it would not be enough to achieve asynchronous loading. With a synchronous interface it is impossible to internally be async. Task.Run(...).Wait();
would be the worst you could do here.
I don't know of a way of extending the ASP.NET pipeline easily but it might be possible. The pipeline already supports asynchronous steps. You might be able to run the loading step at a point in the pipeline where the synchronous session state loading step has not yet run. You load the session state asynchronously even before ASP.NET asks you to. When ASP.NET asks you just hand back the pre-calculated result.
Update: It is easier than I thought. The HttpApplication
class has easy ways of attaching asynchronous event handlers to the pipeline. Just pick one that comes before the point where session state is loaded.
I don't know if this is worth it. Session state operations are usually very fast. Async IO makes the IO use more CPU time. The reason it is attractive on the server is that it unblocks threads. Makes more sense for seconds-long web-service calls then for a 1ms database call.
You can definitely mix sync and async in the same HTTP request, though. So no problem there. Just refrain from calling Wait
or Task.Run
.