caching tutorial caching tutorial - contributed by Nihal Singh

.NET Tutorial > Caching Application Pages and Data

Caching Application Pages and Data

The main issue with web based development is performance. In ASP.NET Opening a database connection and retrieving data is a slow operation. The best way to improve the performance of your data access code is not to access the database at all.

By taking advantage of caching, you can cache your database records in memory. Retrieving data from the cache, on the other hand, is faster.

Caching is one of the best and often easiest ways to improve the performance of an application. With caching, a copy of your data is stored in a location that can be accessed very quickly. The idea with caching is that fetching data from the cache should be faster than fetching it from the original data source. Therefore, most caching solutions store data in memory, which is usually the fastest way to get the data

The ASP.NET 3.5 Framework supports the following types of caching:

  • Page Output Caching
  • Partial Page Caching
  • DataSource Caching
  • Data Caching

Page Output Caching

Page Output Caching caches an entire page. It provides you to cache the entire rendered contents of a page in memory. The next time that any user requests the same page, the page is retrieved from the cache.

You enable Page Output Caching by adding an <%@ OutputCache %> directive to a page.


Code written in .aspx file
<%@ OutputCache Duration=”20” VaryByParam=”none” %>

Code written in .CS file

void Page_Load()
            lblTime.Text = DateTime.Now.ToString();

The above code displays the current server time in a Label control. If you refresh the page multiple times, you will notice that the time is not updated until at least 20 seconds have passed.

When you use the @ OutputCache directive, the Duration and VaryByParam attributes are required. If you do not include them, a parser error occurs when the page is first requested. If you do not want to use the functionality that the VaryByParam attribute provides, you must set its value to None.

Caching Multiple Versions of a Page

ASP.NET allows you to cache multiple versions of a page response declaratively by using attributes on the @ OutputCache directive and its VaryByParam attribute.

Suppose you need to create a separate master and details page. The master page displays a list of employeeID. When you click a employeeID , the details page displays detailed information of that particular employee.When you create a master/details page, you typically pass a query string parameter between the master and details page to indicate the particular employee detail to display in the details page. If you cache the output of the details page, however, then everyone will see the first employee detail selected. You can remove this problem by using the VaryByParam attribute. The VaryByParam attribute causes a new instance of a page to be cached when a different parameter is passed to the page. (The parameter can be either a query string parameter or a form parameter.)


Suppose we have two pages EmpMaster.aspx and detail.aspx.

Code written in EmpMaster.aspx file
Add directive to .aspx page

<%@ OutputCache Duration=”20” VaryByParam=”empID” %>

Code for code behind.

protected void Button1_Click(object sender, EventArgs e)

The page detail.aspx display detailed information of the employee selected from the EmpMaster.aspx page.

You can assign two special values to the VaryByParam attribute:

none: It will ignore any query string or form parameters . Only one version of the page is cached.

* : Causes a new cached version of the page to be created whenever there is a change in any query string or form parameter passed to the page.

You also can assign a semicolon-delimited list of parameters to the VaryByParam attribute when you want to create different cached versions of a page, depending on the values of more than one parameter.

Specifying the Cache Location:

You can use the Location attribute of the <%@ OutputCache %> directive to specify where a web page will be cached. This attribute have the following values:

Any The page is cached on the browser, proxy servers, and web server.
Client The page is cached only on the browser.
Downstream The page is cached on the browser and any proxy servers but not the web server.
None The page is not cached.
Server The page is cached on the web server but not the browser or any proxy servers.
ServerAndClient The page is cached on the browser and web server, but not on any proxy servers.

By default, when you use Page Output Caching, a page is cached in three locations: web server, any proxy servers, and browser.

Using Partial Page Caching

Sometimes it is good to cache an entire page because some part of the page might need to change on each request. When a page contains both dynamic and static content at that time partial page caching is a good choice. For example, you might want to cache a set of database records displayed in a page, but not cache a random advertisement displayed in the same page. By the use of User Control you can perform Partial Page Caching.


In this example we will see how we can use Partial Page Caching.
First we will create a simple user control named CurrentTime.ascx in which we will display the time as user control time.

// Code for CurrentTime.ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="CurrentTime.ascx.cs" Inherits="WebUserControl" %>
<%@ OutputCache Duration="20" VaryByParam="none" %>

<asp:Label ID="Label1" runat="server" Text="User control Time"></asp:Label>

protected void Page_Load(object sender, EventArgs e)
            Label1.Text = DateTime.Now.ToString();

It includes an OutputCache directive, which causes the contents of the User Control to be cached in memory for a maximum of 20 seconds. Because the control includes an OutputCache directive, the entire rendered output of the control is cached in memory.

We will put this User control on the Default.aspx Page.In this page we will again take a label control and display the time.

When you refresh the page, the time displayed by the User control will not changes, but the time displayed in the page will be changed.

DataSource Caching

There are four standard ASP.NET DataSource controls.

  • SqlDataSource,
  • ObjectDataSource,
  • XmlDataSource
  • LinqDataSource

The LinqDataSource control does not support caching and remaining three supports the DataSource caching. By default Caching is not enabled for data source controls, but you can enable it by setting the control's EnableCaching property to true. You have to specify CacheDuration property .The data is refreshed automatically based on the seconds you specify using the CacheDuration property.


Suppose You have taken one GridView that id is EmpGridViev and a SqlDataSource named srcEmployee.

            <form id=”form1” runat=”server”>
                                    id=” EmpGridViev”
                                                DataSourceID=” srcEmployee”
                                                Runat=”server” />
                                                id=” srcEmployee”
                                                SelectCommand=”SELECT * FROM Employee”
                                                ConnectionString=”<% connection string according to your settings %>”
                                                Runat=”server” />

The data are cached in memory for a maximum of 1 hour (3600 seconds). If you are not providing a value for the CacheDuration property, the default value is Infinite.

Data Caching

ASP.NET provides a Cache class that allows you to store objects that require a large amount of server resources to create in memory. Cache class uses key\value pair to store the data. You can place items in the Cache and later retrieve them for use.

The Cache class provides a important method named Insert ().There are several overloaded versions of the Insert () method.

key Specify the name of the unique key as string.
value Provides the value of the new item.
dependencies You can provide one or more cache dependencies, such as a file, key, or SQL dependency.
absoluteExpiration You can provide an absolute expiration time for the cached item. If you don’t need to specify a value for this property, use the static field Cache.NoAbsoluteExpiration.
slidingExpiration The time between when the object was last accessed and when the object should be flushed from the cache. If you don’t need to specify a value for this property, use the static field Cache.NoSlidingExpiration.
priority You can assign values AboveNormal, BelowNormal, Default, High, Low, Normal, and NotRemovable.
onRemoveCallback Called automatically before the item is removed from the cache.


SqlConnection con = new SqlConnection("Provide connection string");
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter("select * from emp",con);
Cache["empData"] = ds; Cache.Insert("empData",ds,null,DateTime.Now.AddHours(1),Cache.NoAbsoluteExpiration);
GridView1.DataSource = ds;

You can use Cache["empData"] in any web page within the application.Its instances private to each application, and it is available only to that particular application. When the application is restarted, the Cache object is recreated.

Cache Dependency

Cache dependency enables you to set the dependency of the cache with some data that can be change. So you can update or remove cache by setting the dependency of cache. There are three types of dependencies supported in ASP.NET:

  • File based dependency
  • Key based dependency
  • Time based dependency

File Based Dependency: File-based dependency comes in picture when particular cache item change that is stored on the disk.

ASP.NET expire cached data items from the cache when the dependency files changes

Key Based Dependency: If we have saved multiple interrelated objects in the cache and if one of the objects changes, we need to update or expire all of them. Key-based dependency checks a particular cache item when another cache item changes.

Time Based Dependency: Time-based dependency causes an item to expire at a defined time. ASP.NET provides two types of time based dependency.

  • Absolute
  • Sliding

Absolute: It provides time for a cache item to expire. The object will be expired from the cache at the specified time. If you don’t need to specify a value for this property, use the static field Cache.NoAbsoluteExpiration.

Sliding: Enables you to resets the time for the item in the cache to expire on each request.You can use sliding dependency when different request are coming for the same item that are available in the cache If you don’t need to specify a value for this property, use the static field Cache.NoSlidingExpiration.

Write your comment - Share Knowledge and Experience

Latest MCQs
» General awareness - Banking » ASP.NET » PL/SQL » Mechanical Engineering
» IAS Prelims GS » Java » Programming Language » Electrical Engineering
» English » C++ » Software Engineering » Electronic Engineering
» Quantitative Aptitude » Oracle » English » Finance
Home | About us | Sitemap | Contact us | We are hiring