views:

2250

answers:

3

I know that most people recommend using HttpRuntime.Cache because it has more flexibility... etc. But what if you want the object to persist in the cache for the life of the application? Is there any big downside to using the Application[] object to cache things?

+10  A: 

As long as you don't abuse the application state, then I don't see a problem in using it for items that you don't want to expire. Alternatively i would probably use a static variable near the code that uses it. That way you avoid to go through HttpApplicationState and then be forced to have a reference to System.Web if i want to access my data.

But make sure to think through how you use the object(s) that you stick in HttpApplicationState. If its a DataSet which you keep adding stuff to for each request, then at some point you end up eating up too much memory on the web-server. The same could happen if you keep adding more items to HttpApplicationState when you process requests, at some point you will force the application to restart.

That's probably the advantage of using Cache in you situation. Consuming larger amounts memory isn't as fatal, since you allow ASP.NET to release the items in your cache when memory becomes scarce.

Tom Jelen
+4  A: 

Use cache when you want items to automatically expire or get reclaimed when memory is scarse. Otherwise use static variables if you can, because they will yield better performance then digging through the ApplicationState collection. I'm not exactly sure what would be the case when to use ApplicationState, but there are sure to be some.

Vilx-
+4  A: 

Application is deprecated by Cache. If you need something with application scope, then you should either create it as a static member of a class or use the Cache. If you want to go the Cache route but don't ever want it to expire, you should use the CacheItemPriority.NotRemovable option when you Insert the value into the cache. Note that it is possible to use this priority and still use cache dependencies, for instance if your data depended on something in the file system. All the CacheItemPriority does is prevent the HttpRuntime.Cache from intelligently clearing the item when it feels memory pressure and uses its Least-Recently-Used algorithm to purge items that aren't seeing much use.

ssmith
Why do you say Application is deprecated? I've never seen this anywhere and its not indicated in the documentation.
Kevin Babcock
Because everything it can do, Cache can do better. There is no reason for Application to exist now that Cache exists, except for backward compatibility.
ssmith