Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use HttpApplicationState rather than Web.Caching.Cache?

When i need to cache something in my application, i used to choose Web.Caching.Cache. But i ran into some legacy code that using HttpApplicationState instead.

Since Web.Caching.Cache is more powerful and flexible (seems MUCH more), is there a situation that better to use HttpApplicationState??

I will be very appreciate if you can show me some examples :-)

like image 319
rhapsodyn Avatar asked May 25 '12 02:05

rhapsodyn


1 Answers

Both HttpApplicationState and Web.Caching.Cache can be used to store information that can be globally accessible throughout an ASP.Net application. However, they have very different uses.

HttpApplicationState is used to store application data that typically does not change. It is typically populated in Application_Start in Global.asax, when the application is starting. I personally have not used it much, but I believe it is typically used to store small pieces of application configuration that are global to all users of an application and which either do not change or change very infrequently. Something put into Application state will remain there indefinitely, until the app recycles. But when it recycles and restarts again, Application_Start will execute again and re-populate it.

It is important to note that HttpApplicationState is a singleton and is not thread safe. So when you make changes to it, you must lock and unlock the Application object via calls to Application.Lock() and Application.UnLock(). Read more

There are actually three different ways you can cache ASP.Net content: Page level, partial page, and data. I am going to talk about data caching, since I think that is most relevant to your question. The ASP.Net cache is used to store large quantities of application data that would be expensive to retrieve from a data store for every request. The key differences between HttpApplicationState and Cache are 1) Cache data is designed to expire and be purged from memory by a variety of triggers or conditions (time, other cache dependencies, etc), whereas HttpApplicationState will be there forever until the app recycles, and 2) Cache data can be purged from memory if a server is experiencing severe memory pressure, and you thus can never count on it being there and must always test to see if it is present, whereas HttpApplicationState will always be there.

Caching is used to store data closer to the application that does not need to be pulled from a database on every request. Caching is designed to store very large quantities of data, and an intelligent caching architecture can have an enormous positive impact on performance.

like image 71
Joe Alfano Avatar answered Jan 03 '23 19:01

Joe Alfano