Possible Duplicate:
ASP .NET Singleton
I know the general differences between singleton class and a class with static properties/methods but I would like to know how it influences the concurrency (many users logged in an application) in a ASP.NET MVC web application? For instance, we are storing settings in our singleton (or static properties) class. Is there a chance that two users suddenly start seeing/sharing the same settings? I mean, if one user changes his settings (being they are stored in memory for the runtime of the app), will it affect the other user? As far as I know the IIS creates one w3wp.exe process for an application, thus all users/visitors will be inside the same process, so could this have an effect on anything?
Short answer, yes, the users will see the same value for any static property. It will be shared between the sessions.
Long answer: yes and additionally if each session is attempting to update shared properties at the same time you can end up with undesired behavior, especially if the shared (static) property is a type that dynamically grows (any collection type). You'll need to handle concurrency when accessing or modifying the values of shared properties.
The only reason to have a singleton or static class is specifically to share one set of values/settings/configuration data with all connections. It keeps memory utilization low if all users need the same information. In this case you'd take care to initialize the values only once or update it atomically using a lock to ensure only one thread is changing the information at a time. Any number of threads could be reading the data without interfering with each other.
If you need different values for different users, it's better to use instance properties as you won't need to worry about concurrence and the performance hit associated with locking.
Static methods are fine. The only real difference between instance and static methods is the manner in which they are called. Even instance methods are held in memory in only one location. Only the instance properties are given their own memory space.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With