DevCity.NET -
Advanced Caching Techniques in ASP.NET 2.0
Sandeep Joshi
Sandeep is a masters graduate in Information Technology. He is having expert hands on Microsoft.NET Technologies as well as J2EE Technology. He has been awarded Microsoft Most valuable Professional twice during his 6 years IT career. He is a well known community speaker. He is also been awarded Microsoft Community Star India in 2002. As a UG Leader he had taken session at Indore .NET User group and is also involved in conducting seminars in Colleges of Indore[India] for .NET awareness. He also runs an educational-portal( with more than 12000 users. His favorite hobbies include playing cricket, singing gajals and writing poems. His mentor is Mr. Amitabh Bachachan besides his Father. Sandeep can be contacted at  
by Sandeep Joshi
Published on 5/5/2006

Web application development is one of the key business process areas in software industry. A web application has a long life only if the user visits the application with interest.

To keep the user interest in your web site, two factors are important. One is easy navigation and the other is fast data retrieval. The most dramatic way to improve the performance of a database driven Web application is through caching.

This article delves into the caching mechanism, available with ASP.NET 2.0. The author takes a walk through ASP.NET 1.1 caching practices as well as a comparison with ASP.NET 2.0 changes.



Data retrieval from a database is one of the resource consuming operations for a web site. To avoid the slower access, you can cache the database data in memory and then you can avoid accessing the database with every page request.

The caching mechanism works in a way that at the very first request your web pages will be stored in the cache and the subsequent requests can be served from the cache.
This reduces network trips to the backend, minimize database access and dramatically increase the performance of your application. Enterprise applications with greater performance and fast access can be developed using caching mechanism available with Microsoft ASP.Net Framework 1.1 and 2.0.

Microsoft ASP.NET framework is a proven technology for developing enterprise applications and you can leverage the benefits of caching in your web application as well. In this article, you'll learn about many of the new caching enhancements in the ASP.NET 2.0 framework. First, you'll learn what we mean by caching and how it is done using ASP.NET Framework 1.1. Next, you’ll learn how caching support has been integrated into the new DataSource controls. Finally, you'll learn how to configure and take advantage of SQL Cache Invalidation.

Caching Fundamentals in ASP.NET Framework 1.1

Cache: A static object with a collection dedicated to storing and processing cache information (System.Web.Caching.Cache).

Cache Dependency: It is a mechanism through which the cache data can be made dependant on any file or a key data present in the cache itself.

Cache Expiration: It provides a way to provide expiration to the data available in the cache. In ASP.NET 1.1, we have absolute and sliding expiration policies.<o:p></o:p>

Cache Callback: It is a delegate, which can be associated with any cache item. It is invoked when the associated item in the cache expires due to any reason. The expiration reasons can be any of the following:

1. Removed: The item is explicitly removed from cache.

2. Expired: The item’s time is expired due to cache time out or its own expiration policy settings.

3. Underused: The cache item is removed from the cache due to shortage of resources.

4. Dependency Changed: The cache item is removed from the cache because its dependency has been changed.

ASP.NET 1.1 Caching Techniques

Page Output Caching

The output of a web page is the rendered HTML contents. You can cache the output of whole the page with the help of Page Output Cache technique. The output caching can be enabled using a page directive. The page directive is as follows:

<%@ OutputCache Duration="60" VaryByParam="none"%>

The directive specifies that the output of the page will be cached for 60 seconds and no query string parameter will affect the cached page. The duration is in seconds and can be up to 300 seconds. To give you a clear picture of the VaryByParam attribute, let’s assume that the page we have developed is having the name test.aspx and it is in the solution named cachingPractice. To browse this page, you will write following URL in your browser


This will take you to the test page. Now see the URL carefully. There is no parameter passed with the URL. So in the cache we will have a version for the page with no parameter for next 60 seconds. It means for the next 60 seconds all the requests will be served with the available cache version and the page will not be executed at all. If a request comes after 60 seconds then the page will be executed again and brought to the cache again.

Now for instance, I have changed the Cache Page directive as below:

<%@ OutputCache Duration="60" VaryByParam="PageId"%>

And my requested URL is


In this case, for the PageId parameter which is passed in querystring, a new version of page is created for 60 seconds. Each request with PageId=a1 will get the same output for next 60 seconds. If somebody requests the page with PageId=a2, then a new version of page is created for the new value of PageId parameter which will last for 60 seconds.



Fragment Caching:

When you don’t want to cache the entire page, but the part of a page then fragment caching can be used to cache the page fragment. Fragment caching can be done using user controls. A user control will hold the part of the page which you want to put in cache. The cache directive will be place in the .ASCX file for that control. In this case only the output of the user control will be kept in the cache.


Data Caching


ASP.NET cache object supports data caching. You can save you data in the cache using a key value pair. This kind of caching is done through programming and no directive is needed. You will have to import System.Web.Caching namespace in code behind file. Cache is a static/shared object and you don’t need to create an instance for this object.

Cache ("key") = value ‘store value or object

var = Cache ("key") ‘retrieve value or object

Here the key represents a string and the value represents an object. You can store any object in the cache. By default the data stored in the cache will remain in memory for the time specified in outputCache duration attribute. However, with the help of expiration policy we can control the expiration time for each data item in the cache.

In ASP.NET 1.1 Framework, we have 2 types of expiration policies.


1.Absolute expiration Policy

In this expiration, an absolute time period is defined after which the item will be expired from the cache in any case.



Cache.Insert("key", value, Nothing, Now.AddSeconds(10), Cache.NoSlidingExpiration, CacheItemPriority.High, Nothing)


This code will add the value (object) in the cache with the key as “key” for 10 seconds. After 10 seconds the value will be removed from the cache.


2.Sliding Expiration Policy

In this expiration, a time span is defined. If the item is not used in that time span then it will be removed from the cache else it will again occupy the cache for the next time span whenever used.



Cache.Insert("key", value, Nothing, Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(10),

CacheItemPriority.High, Nothing)

The insert method used above takes 7 parameters. Currently we have taken 3rd and 7th parameter as nothing. The 3rd parameter specified the Cache Dependency. We can specify two types of dependencies in ASP.NET 1.1 Framework.


  1. Key Dependency: When the cache item is dependant on another cache item, then key dependency is used.



Dim keyarr() As String = New String() {"key1"}

Cache.Insert("key2", value, New CacheDependency(Nothing, keyarr))


This code specified that the “key2” is dependant on the keyarr. It means whenever the “key1” value in the cache is altered; the “key2” will be removed from the cache.


  1. File Dependency: When the cache item is dependant on a file, then file dependency is used.


Cache.Insert("key3", object, New CacheDependency(Server.MapPath("a.xml")))


This code specified that the “key3” is dependant on the file “a.xml”. It means whenever the file “a.xml” is altered; the “key3” will be removed from the cache.

Cache Callback

Sometimes it is required that we want to execute certain code when a particular item is removed from the cache. Since the removal is done in background, we need to use a delegate for this purpose. ASP.NET Framework 1.1 provides a delegate to solve this problem. In the Caching Namespace we have CacheItemRemovedCallback delegate which takes a subroutine address as a parameter. The subroutine address is the address of a method which takes three parameters. 1. A String which represents the Key in the cache. 2. An Object which represents the values of the key 3. A CacheItemRemoveReason enumeration gives us the reason forremoval. The delegate can be used as follows:


  • Create a Subroutine with 3 parameters as follows and write the code that you want to execute on removal of the item.


Sub ONITEMREMOVED (ByVal key As String, ByVal value1 As Object, ByVal r As CacheItemRemovedReason)

Cache.Insert(key,value1,Nothing,Cache.NoAbsoluteExpiration,TimeSpan.FromSeconds(10), CacheItemPriority.High , Nothing)

End Sub

  • Create an object for the delegate and pass the address of the subroutine created in step 1.

    Dim MyCacheDelegate As New CacheItemRemovedCallback(AddressOf ONITEMREMOVED)

Specify the delegate object while inserting the item in cache.


Cache.Insert("key", value, Nothing, Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(10),

CacheItemPriority.High, MyCacheDelegate)

Through this code, whenever the item “key” is removed from the cache, it will invoke the MyCacheDelegate delegate.

Limitation of ASP.NET 1.1 Caching Mechanism

In ASP.NET 1.1, you can invalidate a cached item based on some pre-defined conditions such as change in an XML file or change in another cache item (Dependencies). Using this mechanism the item is removed from the cache when the file or another cached item changes. We can not refresh the item directly. The ASP.NET 1.1 Cache API does not allow you to invalidate an item in the cache when data in a SQL Server database changes.



A new wave: ASP.NET 2.0 Caching

One of the biggest changes in the ASP.NET 2.0 framework concerns how you access database data in an ASP.NET page. The ASP.NET 2.0 framework includes a new set of controls, known collectively as the DataSource controls, which enable you to represent a data source such as a database or an XML file.
In the ASP.NET 1.1 framework, the controls are bounded with DataSet or DataReader. In the ASP.NET 2.0 framework, we bind a control to a DataSource control instead. The DataSource control is having a better functionality and greater capabilities. It minimizes the code to be written to develop a database driven page. In ASP.NET 2.0 following three DataSource controls are there:
SqlDataSource: Represents any SQL data source, i.e. Microsoft SQL Server or an Oracle database.
AccessDataSource: A specialized SqlDataSource control designed for working with a MS Access.
ObjectDataSource: Represents a custom business object that acts as a data source.

Caching with the DataSource Controls

Th DataSource controls provide direct support for caching the database data. The DataSource control properties can be defined to cache automatically the data represented by a DataSource control in memory.

For example, if you want to cache the Northwind database table in memory for at least 10 minutes, you can declare a SqlDataSource control using following code:

SelectCommand="SELECT CategoryId FROM Categories"Runat="server" />

The EnableCaching property controls automatic caching of the data retrieved by the SelectCommand. The CacheDuration property specifies the duration of caching.

By default, the SqlDataSource will cache data using an absolute expiration policy. This can also be configured to use a sliding expiration policy.

SQL Cache Invalidation: The Most Awaited

SQL Cache Invalidation is one of the most anticipated new features of the ASP.NET 2.0 framework. It is a mechanism which enables you to automatically update data in the cache whenever the data changes in the underlying database.

How it works?

SQL Cache Invalidation works by constantly polling the database to check for changes. After every definite milliseconds period, the ASP.NET framework checks whether or not there have been any changes to the database. If the ASP.NET framework detects any changes, then any items added to the cache that depend on the database are removed from the cache (they are invalidated).
SQL Cache Invalidation only works with Microsoft SQL Server version 7 and higher. This is not supported in MS Access or Oracle.
Configuring SQL Cache Invalidation
To configure SQL Cache Invalidation, we have to perform following steps:
1.Configure SQL Server to support SQL Cache Invalidation
2.Configure Application’s Web Configuration File
Configuring SQL Server for SQL Cache Invalidation
To configure SQL Server for Cache Invalidation we can either use the aspnet_regsql command line tool, or SqlCacheDependencyAdmin class. We’ll configure using aspnet_regsql tool.

Enabling SQL Cache Invalidation with aspnet_regsql tool

The aspnet_regsql tool is a command line utility to enable SQL Cache Invalidation. The aspnet_regsql tool is located in your Windows\Microsoft.NET\Framework\[version] folder. This tool can be directly run using “Visual Studio .NET Whidbey Command Prompt” option in the Programs Visual studio tools Menu. If you run this tool directly, this will start a wizard which looks like the figure 1a. However, to set the SQL Cache Invalidation, we need to use it with certain arguments.
In order to support SQL Cache Invalidation when using the Northwind database, you need to execute the following command.aspnet_regsql -E -d Northwind -ed
The -E option causes the aspnet_regsql tool to use integrated security when connecting to your database server. The -d option selects the Northwind database. Finally, the -ed option enables the database for SQL Cache Invalidation.
This command creates a new table named AspNet_SqlCacheTablesForChangeNotification in the database. This table contains a list of all of the database tables that are enabled for SQL Cache Invalidation. The command also adds a set of stored procedures to the database.After this, you need select the particular table in the database to which you want to enable the Cache Invalidation. The following command will do that:
aspnet_regsql -E -d Northwind -t Categories –et
The -t option selects a database table. The -et option enables a database table for SQL Cache Invalidation. For multiple tables, you need to execute the command for each table.
This command adds a trigger to the database table. The trigger fires whenever you make a modification to the table and it updates the AspNet_SqlCacheTablesForChangeNotification table.

Application Web Configuration Settings for SQL Cache Invalidation

The next step is to configure the ASP.NET framework to poll the databases that you have enabled for SQL Cache Invalidation. Following listing is the web.config file for your application.
Web.Config File listing

In the Web configuration file, the <CONNECTIONSTRINGS>section is used to create a database connection string to the Northwind database named CacheSqlServer.
The section is used to configure the SQL Cache Invalidation polling. You can specify different polling intervals for different databases in the section.




For enterprise application, where data retrieval is a big issue, caching can enhance the performance in a dramatic fashion. With the launch of ASP.NET 2.0 framework, significant changes have been made to the caching mechanism to reduce the programmer’s headache.

The new DataSource controls include properties that make it easy to cache database data in memory without writing any code. The new support for SQL Cache Invalidation enables you to automatically reload database data in the cache whenever the data is modified in the underlying database. This feature provides you with all the performance benefits of caching, without the worries of the database changes.