21 - Web Caching and ASP.NET

21.1 Introduction of Caching

Caching is used for storing the data that needs to be constantly used in a system. The data is stored in the memory as the data retrieval is easier for the end user. ASP.NET supports cache API for storing arbitrary data and an output cache to store the requested pages in an application.

Caching enables user to improve the performance of Web applications. It reduces the load on the server. It is extensively used to enhance the performance of the application. The benefits of using caching are as follows:

1) Less Bandwidth: The cache location can be configured on the client system. The requests and responses don not travel in the network between the client and the server. Thus the bandwidth is reduced.

2) Reduced access time: The requests are processed by the cache itself and do not go to the server, the access time is reduced

3) Less Load on server: The ASP.NET code is not executed repeatedly to create same result. Thus the CPU usage is reduced and the load on the server is lowered

4) Stability: The stability of the application is increased due to the implementation of caching in it

21.2 Output Caching

Output caching improves the performance of an ASP.NET application by caching the markup for the ASP.NET page. If the page is frequently requested by the user within the specified period of time, ASP.NET serves the cached page to the user. The output cache technique is useful when the web page is rarely changed.

Consider an example of shopping website. The products page contains the details of all the products from the database table. If the output caching is not implemented, each time the page is accessed by the user, the connection is made to the database. The query operation is performed and the result and the output s returned to the client. It takes time and the performance of the server is affected.

If the Output Caching is implemented, when the products page is first visited, the rendered HTML is cached for a specific duration. If during the specified time the page is again requested by the user, the Cache markup is returned to the user. It saves the database access and page rendering time.

To implement Output caching, insert the @OutputCache directive at the top of the .aspx file. The syntax of adding it is as shown below:

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %>
<%@ OutputCache Duration=”20” VarByParam=”None” %>

In the above example, the @OutputCache directive contains two attributes Duration and VarByParam. The Duration attribute uses the ASP.NET page to cache the page for the specified number of seconds. The VarByParam attribute copies the page that needs to be saved. The value None indicates that only one copy of the page is to be cached.

If the user wants to save more than one copy of the web page, the VarByParam values differ in the syntax. The syntax is as shown below:

   <%@ OutputCache Duration=”20” VarByParam=”*” %>

21.3 Data Caching

Data Caching is used to store the frequently used data in the built-in collection object called Cache. It is the property of the Page class and it returns the instance of the System.Web.Caching.Cache class. The Cache object works similar to the Application object.

The Cache object is available globally to all requests from all the clients in the application.

The Cache object is different to the Application object in many ways as listed below:

1) The Cache object does not need to be explicitly locked or unlocked by the user

2) All the items in the Cache object are removed automatically from the system

3) All the items in the Cache object are linked to a file, a table, a database, or any other resource

Data Caching can be implemented programmatically. The Cache class encapsulates data caching and an object of the Cache class is created for implementing data caching. All the items are stored in key-value pair.

Consider an example for storing a variable in the Cache object. Create a variable by name, uname in the Cache object. The code snippet is as shown below:

     Cache[“uname”] =”Sam”;

The code snippet to retrieve the value from the Cache object is as shown below:

    TextBox1.Text=Cache[“uname”];

The life of the Cache object associated with an application is similar to the life of the application. Hence, when the application stops the information in the Cache object is lost.

21.4 Object Caching

In OutputCache directive entire page or user control is cached by the user. Sometimes there is a need for caching an object in an application. User can place object in the cache. The data type of the object can be a control, a class, a DataSet object, etc.

Consider a sample code to demonstrate the cache object store the information of ArrayList with custom objects in it.

protected void Page_Load(object sender, EventArgs e)
{
  ArrayList stamps;
  if ( Cache[“stamps”]==null)
  {
    stamps=new ArrayList();
    stamps.Add(DateTime.Now);
    stamps.Add(DateTime.Now);
    stamps.Add(DateTime.Now);
    Cache.Add(“stamps”, stamps, null,System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0,0,60),
    System.Web.Caching.CacheItemPriority.Default, null);
  }
  else
  {
    Stamps=(ArrayList)Cache[“stamps”];
    foreach(DateTime dt in stamps)
    Response.Write(dt.ToString()+”<br/>”);
  }
} 

Execute the code and 3 instances of current date is placed in the ArrayList. The list is cached using the Cache object in an application. The CacheDependency parameter is used to cache item depends on other items. It contains two parameters as how and when the item will expire in the cache. The first parameter defines the item can expire at any time of the certain day. The TimeSpan class is used to specify that it will expire after 0 hours, 0 minutes and 60 seconds. The priority can be set for an item in a cache.

Depending on the priority assigned, items are removed from the list. The last parameter is used to specify the callback function for the item. In the code it is assigned to null.

Like us on Facebook