Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton class or a class with static methods in ASP.NET MVC application [duplicate]

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?

like image 709
mare Avatar asked Dec 07 '10 22:12

mare


1 Answers

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.

like image 86
Erik Noren Avatar answered Sep 28 '22 02:09

Erik Noren