Which is better: static variable V.S. Launching an Asp.NET Application?

Suppose you want to share some resource, such as a class or variable, in all threads / sessions in an ASP.NET web application. What's better?

1) A static variable having thread-safe means of accessing this static variable?

2) Or an ASP.NET application session variable?

+7
global-variables static-members
source share
4 answers

If you have only one of them, the difference is small.

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

+7
source share

Static members will offer better performance, but the downside is not thread safe:

It is recommended that data be stored in the static members of the application class, and not in the Application object. This improves performance because you can access a static variable faster than accessing an element 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

+4
source share

This is a common scenario in which you view multiple pages and collect data. I would use a Session object for this scenario. Static variables should be used when a complete application needs the same object.

If the value you want to save depends on the user, then use Session.

0
source share

Real session variables should only be used if you want to keep the value for the entire session, but if you want the variables to be initialized and used between forms, and if they were changed in betwwen, accessible through the entire application for the same object, must use static variables.

0
source share

All Articles