ASP.NET Caching

There are a few types of caching in ASP.NET, specifically Page Output Caching and Object Data Caching. There are whole hosts of articles out there on using the cache, but for the purposes of this post, I’m going to talk about just using Object Data Caching. To many, this will be obvious, but some cache code I wrote recently made me remember that this can sometimes be confusing in the context of an ASP.NET page.

Typically, you can access the cache from just calling Cache.Add or HttpContext.Curent.Cache.Add. This gives you access to the application wide Cache object. Any object you cache here will be available to any class within your application for the time period you specified for the cached object.

But what if you want to just cache an object for a request? Say you have an item object that you reference on 4 or 5 controls on a page? You don’t want to go to the DB to get the data each time you reference it. Instead, use the HttpContext.Current.Items collection and put your object there. It will be good for the duration of the request.

The two are very different. The first will make your cached data available application wide, to all requests. This can be dangerous if the data might be different for one user than it is for another. The second is available only to the current request. Use this if you load up an object say from the database in one control, but need it in subsequent controls that make up the same request.

Be careful with your cached objects and keep an eye on where you’re putting them. Not doing so can have some potentially disasterous effects.

3 thoughts on “ASP.NET Caching

  1. SeemaSingh

    Hi,

    With the little knowledge i have in .net i think the above article is nothing but junk.

    Regards,
    SeemaSingh

  2. Ali Asghar

    Hi Seema,
    I dont understand why the above article is a junk. Can you please explain?

    This article explains the use of HTTPContext for storing the temporary data which is required within just one request. This might not be useful in normal page lifecycle coding (as your page data and variables are available with you in a request), but this is very useful when you want to share data between HTTPModules or HTTPModule and HTTPHandler.
    Using current context in normal coding practice instead of sessions or cache can avoid memory leaks too.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.