How to use the System.Web.Caching.Cache Object – ASP.NET Data Caching

Data caching is storing of data in web-server’s (IIS) memory for quick access by requesting browsers.  Any information that is expensive to get (in terms of performance) is saved in the data cache. For example, commonly SELECTED database values that do not change often can be stored in data cache.  This way instead of making repeated calls to SELECT data from dB, it can be accessed only one time and saved into the cache. Future requests to the same data will be retrieved from the cache as opposed to database call, thus reducing the load on database server.

Using data caching, you can cache selected data objects as opposed to the entire page. Read my post ASP.NET 4.0 Output Caching if you need cache the entire page in HTML format.

Using ASP.NET 4.0 Data Caching

The System.Web.Caching namespace has two classes Cache, and CacheDependency that are used to provide caching functionality.

 

Cache Object

Asp.net Cache Object provides caching functionality. A cache object resides in the Application Server’s memory. The timeout property of the Cache object indicates when will the cache expire. Cache objects are similar to Application variables with some minor difference:

What is the difference between application state and caching

Application variables exist as long as the application is alive. Cache objects have  timeout property, which allows us to control the duration of the Objects to live. Another usefulness in caching is that we can define the way we cache our output since caching can be done in 3 ways

  • Full Page – defined in page directive
  • Partial Page – Example:  User controls (.ascx)
  • Data / Programmatic caching. using the Properties of Cache object such as Cache.Insert

Lets discuss Data or Programmatic caching using the Cache object.

protected void Page_Load(object sender, EventArgs e) {
    x = System.DateTime.Now.ToString();
     if (Cache["ModifiedOn"] == null) { // first time so no key/value in Cache
        Cache.Insert("ModifiedOn", x); // inserts the key/value pair "Modified On", x            
     }
     else { // Key/value pair already exists in the cache
         x = Cache["ModifiedOn"].ToString();
     }
}

In the above code we are inserting the current time string into a cache object called “ModifiedOn” the very first time the page is accessed.  Further requests to this page simplyacces this object and return the value associated with the key “ModifiedOn”. When you run this application you will see the current time at the time of running this application first time. From second time onwards the same string is displayed, until you reset the application.

Using the CacheDependency Object to link the Cache state to XML File time stamp

In the Insert () method of the Cache object, you can optionally give a CacheDependency Object that is constructed from an XML file. In this below example, I am saving the data ina XML file called XMLFile1.xml in the App_Data folder under my Application1 root. The file contains only one variable called userid.

<?xml version="1.0" encoding="utf-8" ?><userid>Anjelina Jolie</userid>

The first the Page_Load() is called I read this file and get the userid out of it and save it in variable y. I also create a Cache Object wth key “userid” and set the value to y and give optional CacheDependency object created from XMLFile1.xml using

Cache.Insert("userid", y, new CacheDependency(Server.MapPath("~/App_Data/XMLFile1.xml")));

The above Insert will make the Cache Object depend on the timestamp of the XML file. In other words, if you edit the XML file and change the userid and save it, the Cache Object immediately gets expired. so Cache["userid"] will return a null.

Each additional request, I simply get the Cache ["userid"] object and assign that to y.

protected void Page_Load(object sender, EventArgs e) {
    XmlDocument doc = new XmlDocument();
    doc.Load(Server.MapPath("~/App_Data/XMLFile1.xml"));
    XmlNode root = doc.DocumentElement;
    y = root.InnerText;
    y += " - Cached at " + System.DateTime.Now.ToString();
    if (Cache["userid"] == null) { // first time so no key/value in Cache
        Cache.Insert("userid", y, new CacheDependency(Server.MapPath("~/App_Data/XMLFile1.xml")));
    }
    else { // already cached before
        y = Cache["userid"].ToString();
    }
}

My Aspx page looks like this:

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"  CodeBehind="LearnCaching.aspx.cs" Inherits="WebApplication1._Default" %><asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"></asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<h2>Current Time From Cache is:</h2><%=x %>
<h2>Userid from XMLFile1.xml is:</h2><%=y %>
</asp:Content>

This entry was posted in ASP.NET, Caching and tagged , , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

One Trackback

  • By ASP.NET 4.0 Output Caching on March 29, 2011 at 8:11 am

    [...] Read my post about Data Caching:  ASP.NET Data Caching – How to use the System.Web.Caching.Cache Object [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>