ASP.NET Static classes and asp.net sessions
-
04-07-2021 - |
Question
Would someone be kind enough to explain or point to article that explains how the scope of static classes and methods interact with the scope of a ASP.NET user session.
Here is the more specific situation which explains my question:
- User A logs into a asp.net website.
- While doing something user A uses a static method which initializes some data.
- User B logs into the same asp.net website.
- User B hits the same static method.
Is the data already initialized once user B hits it?
Also what if the asp.net session of user A expires before user B hits the website?
Solution
Static data lives as long as the process is running. It is attached to the type.
If the data that is initialized is in a static context, then when user B hits the method, it will already be initialized.
Sessions are not relevant here - only the process.
If the process gets recycled, then the data will have to be reinitialized.
OTHER TIPS
Check these posts: Why does my ASP.Net static function's "context" crossover between user sessions?
What is the scope of a Static Class?
C# Static variables - scope and persistence
http://msdn.microsoft.com/en-us/library/ms173138(v=vs.100).aspx
In short:
Is the data already initialized once user B hits it?
Yes
Also what if the asp.net session of user A expires before user B hits the website?
User B will access data initialized by user A
Static data is shared among the entire application domain of your webapp. It's shared among all the threads serving requests in your webapp, it's not bound to a session/thread/user in any way but to the webapp as a whole.