views:

67

answers:

2

For my global variables and data I find myself in a dilema as to whether to use HttpApplicationState or Static variables - What's the best approach?

This document states that one should use static variables over httpapplicationstate: http://support.microsoft.com/default.aspx?scid=kb;en-us;Q312607

However, one thing I like about HttpApplicationState (and System.Web.Caching.Cache), is that one can easily enumerate the entries and select which items to remove (I've created a global CacheManager.axd for this purpose), whereas I don't believe there's an easy way with Static variables (and even then it's not clear what to do to "re-initialise" them), without recycling the app pool.

Any suggestions on a neat general-purpose way to handle and manage global objects?

Thanks, Mark.

+1  A: 

Your instincts are correct. Use System.Web.Caching. The built-in cache management takes care of all the heavy lifting with respect to memory allocation and expiring stale or low priority objects.

Make sure to use a naming convention, for your cache keys, that makes sense down the road. If you start relying heavily on caching, you'll need to be able to target/filter different cache keys by name.

sohtimsso1970
A: 

As a general practice, it's good to try to avoid global state in web applications when possible. ASP.NET is a multithreaded environment where multiple requests can get serviced in parallel. Unless your global state is immutable (readonly), you will have to deal with the challenges managing shared mutable state.

If your shared state is immutable, and you don't need to enumerate it, then I see no problem with static variables.

If your shared state is volatile/mutable, then you probably want to create an abstraction on top of whichever underlyig mechanism you choose to store the data to ensure that access and modification of that shared state is consistent and complies with the expectations of the code that consumes it. I would probably use the system cache in such a design as well, just to be able to leverage the expiration and dependency features built in to the caching service (if necessary).

LBushkin