What is better: Static variable V.S. Asp.NET Application Session?

Say you want to share some resource, like a class or a variable across all threads/sessions within a ASP.NET web application. What is better?

1) A static variable having thread-safe accessors to that static variable?

2) Or a ASP.NET application session variable?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

If you only have one of those, there is little difference.

If you have several, you should use static variables rather than Application variables. The Application.Lock method will lock all Application variables, while you can use separate syncronisition identifiers for your static variables, so that each lock only affects the code that accesses that specific variable.

Method 2

Static Members will offer better performance, but the down-side is they are not thread safe:

It is recommended that you store data in static members of the application class instead of in the Application object. This increases performance because you can access a static variable faster than you can access an item in the Application dictionary.

From: http://support.microsoft.com/default.aspx?scid=kb;en-us;Q312607

and:

http://weblogs.asp.net/plip/archive/2003/12/01/40526.aspx

Method 3

This is a common scenario in which you are going through multiple pages and collecting data. I would use a Session object for this scenario. Static variables should be used when the complete application is in need for the same object.

If the value you want to hold is dependent on the user then use Session.

Method 4

That’s true session variables should only be used for if you want to store the value for the whole session, but in the case you want the variables to be intitialized and to be used in between the forms and if changed in betwwen should be available through the whole application for the same object must use static variables.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x