Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 328
7wp Avatar asked May 21 '09 17:05

7wp


2 Answers

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.

like image 69
Guffa Avatar answered Oct 15 '22 17:10

Guffa


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

like image 42
atconway Avatar answered Oct 15 '22 19:10

atconway