alexey
alexey

Reputation: 8480

Static variables in ASP.NET

There is an article that recommends to store ASP.NET application state in static members of HttpApplication class (in Global.asax.cs).

What about storing application state in static members of other classes?

I tried to do so and it seems that there are several instances of these variables can exist (single instance per AppDomain?). Is it true and should we always use only Application class's static fields? Or it doesn't matter?

Upvotes: 3

Views: 825

Answers (3)

Ryan
Ryan

Reputation: 641

You can run into big problems with static variables if you are doing anything more than just reading from them in a web application. Asp.net is a multithreaded environment. The application collection does locking for you during a Get or a Set with a lock. If you use static variables, then there is no lock in place.

I would suggest using the web.config to store all your read only variables in it's own section.

Upvotes: 3

Joel Coehoorn
Joel Coehoorn

Reputation: 416149

Is it true and should we always use only Application class's static fields?

Yes. User-specific data (session data) should not go here.

All the users of your site are in the same application instance, and so will share the same static variables. It's definitely not a good replacement for the session, for example.

Upvotes: 1

Mehrdad Afshari
Mehrdad Afshari

Reputation: 422290

It works pretty well and it's better than Application in many cases (it's strongly typed, for instance). Just make sure you are aware of threading and locking issues.

As a personal experience, I've managed to cache configuration information for ASP.NET app in a static class in a couple Web sites.

Upvotes: 3

Related Questions