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
).
priority
� CacheItemPriority
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.
if(!IsPostBack)
Cache["ProductData"]=GetDataSet();
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:
XmlDocument xd = new XmlDocument();
d.Load(Server.MapPath("product.xml");
Cache["ProductData"]=xd;
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:
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:
<%@ OutputCache Duration="10" %>