Click here to Skip to main content
15,867,771 members
Articles / Web Development / ASP.NET
Article

Caching in ASP.NET

Rate me:
Please Sign up or sign in to vote.
1.22/5 (18 votes)
16 Sep 20043 min read 78.7K   34   2
Page caching in ASP.NET. We can increase performance of the web page using caching, and also reduce server request traffic.The way to improve the throughput is to use caching in web pages.

Introduction

Caching is one of the features in ASP.NET which has been improved to a great extent as we move from conventional ASP to ASP.NET. Caching is helpful in improving the efficiency and speed of your web-page. You can do a lot in ASP.NET which would be clearly visible in the form of a fast application in .NET. Page caching in .NET is highly improved and has advance features like relating cache items with their dependencies. ASP.NET has several facilities for supporting caching: a Cache API for storing arbitrary data and an Output Cache used to store frequently requested pages. Following is a brief article which gives you a quick view of using Cache API in ASP.NET.

Rather than storing our data as key/value pairs in the Application or Session collection, we can store it in the Page.Cache. Its function is conceptually similar – to store a name/value pair on behalf of the application. The differences become apparent when you look at the parameter lists of the Add functions for Application and Page.Cache, however. In addition to the name/key and value parameters, Page.Cache.Add has the following parameters:

  • dependencies – a CacheDependency object indicating what this cache entry’s data is dependent on.
  • absoluteExpiration – a DateTime indicating the absolute date and time when the data in this cache entry should be considered invalid (DateTime.MaxValue disables this functionality).
  • slidingExpiration – a TimeSpan indicating the elapsed time since last usage that will render cache entry invalid (TimeSpan.Zero disables this functionality, cannot be used in conjunction with absoluteExpiration).
  • priorityCacheItemPriority enumeration indicating the priority of this item in the ASP.NET cache.
  • onRemoveCallback – a callback function enabling the application to take action when the data is removed from the cache.

To simply take advantage of Cache, we can simply store a DataSet into the cache. This will increase the speed of page execution as no query would be made to the database for fetching the DataSet every time. We can simply put a check before storing the DataSet into a cache variable, which will get DataSet only if the DataSet is not already saved in the cache.

C#
if(!IsPostBack)
     Cache["ProductData"]=GetDataSet();

//GetDataSet() is a function which returns a dataset 
//which is to be stored in Cache

The above mentioned code is similar to storing variables in an Application or Session Object. The real benefit of Cache in ASP.NET lies in using its special features like "Cache Dependencies" on Files, keys, and time. Following examples explain the use of it.

File-based dependency invalidates a particular Cache item when file(s) on disk change. For example, if instead of loading our product data from a database, we load it from an XML file:

C#
XmlDocument xd = new XmlDocument();
d.Load(Server.MapPath("product.xml");
Cache["ProductData"]=xd;
C#
//Creating Dependencies
CacheDependency depends = new CacheDependency("product.xml");
Cache.Insert("ProductData", xd, depends);

Any changes in the XML document "product.xml" will invalidate data in Cache["ProductData"].

Taking the Cache Beyond the Page

It is clear that the Page cache offers more functionality than the Application collection, but with more limited scope. How can we take advantage of this functionality for data that is used by more than one page? Fortunately, this can be achieved by storing the cached data in the Application collection, and merely using the Page.Cache to let us know when the dependency changes, using the onRemoveCallback. This can be done from a single class shared by all pages that need to access the data:

C#
public static ProductList GetProductList(System.Web.UI.Page page)
{
    ProductList productList = (ProductList)page.Application[productListTag];
    if (null == productList)
    {
        productList = new ProductList();
        productList.ReadXml(page.Server.MapPath(_productListFile));
        Page.Cache.Add(_productListTag,page.Application,
             new CacheDependency(Page.Server.MapPath(_productListFile)),
             DateTime.MaxValue,
             TimeSpan.Zero,
             CacheItemPriority.NotRemovable,
             new CacheItemRemovedCallback(RemoveCallback));
        Page.Application.Add(_productListTag,productList);
    }
    return productList;
}

private static void RemoveCallback(string tag, object obj, 
                                   CacheItemRemovedReason reason)
{
    HttpApplicationState Application = (HttpApplicationState)obj;
    if(CacheItemRemovedReason.DependencyChanged == reason)
    {
        Application.Remove(tag);
    }
}

Page Output Caching

Page output caching is a feature of ASP.NET that allows for the entire contents of a given page to be stored in the Cache. This is helpful, if you want to store the entire web-page for a duration of time. This should be used when a page data is viewed very frequently and data on the page doesn't change so often. This can be done by simply adding a directive on the .aspx file as follows:

ASP.NET
<%@ OutputCache Duration="10" %>

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Question&quot;a more limited&quot; scope? Pin
Alberto Venditti24-Feb-05 8:19
Alberto Venditti24-Feb-05 8:19 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.