<%@ Page %>

Caching Techniques In ASP.NET - Part II


In the Part-I of this article we saw how to use page and user control output caching features. In this part we will learn about application data caching features of ASP.NET.

What is Data Caching?

Just like we can cached the output of web forms and user controls we can also cache data i.e. variables, objects of our application. This is possible via a special object called Cache. Cache object is similar to application object in that it exists for the entire application. It differs from application object in that it can be automatically 'freed' by ASP.NET in case of system resources becoming scarce. You can add, insert or remove items to Cache object. You can also set priority of the individual items and decide when to reclaim resources by the item.

Adding items to the Cache

Let us start by examining how to add new items to the Cache.
Dim emp As New Employee()
emp.Name = "Bipin"
emp.Age = 26
Cache("myemp") = emp
Here, we have created instance of custom class Employee. Cache stores our data as key-value pairs. This syntax is similar to using Application or Session objects. In addition to above method we can also use Insert method of Cache object to add new items.
Dim emp As New Employee()
emp.Name = "Bipin"
emp.Age = 26
Cache.Insert("myemp", emp)
There is also Add method that can be used to add new items to the Cache but it takes many other parameters that we have not discussed yet.

Retrieving item from Cache

Following code shows how to retrieve items that we store previously in the Cache.
Dim emp As Employee
If Not Cache("myemp") Is Nothing Then
	emp = CType(Cache("myemp"), Employee)
	Response.Write("Nothing in cache!")
End If
Alternatively, you can also use Item property to get a specific item:
Dim emp As Employee
If Not Cache.Item("myemp") Is Nothing Then
	emp = CType(Cache.Item("myemp"), Employee)
	Response.Write("Nothing in cache!")
End If
While working with cache it is a good practice to always check it the item already exists in the cache. This is necessary because ASP.NET many remove the item based on dependency set or if resources became scarce.

Removing items explicitly

You may remove items cached previously explicitly using Remove method of Cache object.

Removing items based on disk file timestamp

This is one of the powerful features of ASP.NET caching. You can set dependency between the cached item and disk file such that whenever the disk file is modified the cached item is removed. The example shown below assumes that you have a product catalog markup in catalog.htm file.
If Cache.Item("mycatalog") Is Nothing Then
	Dim strcatalog As String
	Dim sr As StreamReader
	sr = File.OpenText(Server.MapPath("catalog.htm"))
	strcatalog = sr.ReadToEnd()
	Cache.Insert("mycatalog", strcatalog, New 
End If
  • We first check if item already exists in the cache
  • If not we read a disk file that represents a product catalog into a string variable
  • We then store this string in the cache
  • We have associated the disk file with the cached item by using CacheDependency class.
This means that whenever catalog.htm changes the cached version of mycatalog item will be removed. Since we are checking for availability of cached item it will ensure that latest version of catalog is always available in the cache.

You can also specify multiple files as array in one of the overloads of the CacheDependency class constructor.

Removing items based on another cached item

You can also remove an item from the cache when another cached item changes. Following example will make it clear.
If Cache.Item("mykey") Is Nothing Then
	Cache.Insert("myanotherkey", "myanothervalue")
	Dim cachekeys(0) As String
	cachekeys(0) = New String("myanotherkey")
	Dim myvalue As String = DateTime.Now.ToString
	Dim cd As New Caching.CacheDependency
	(Nothing, cachekeys)
	Cache.Insert("mykey", myvalue, cd)
End If
  • We added an item with key myanotherkey
  • We then created a string array that stores keys on which we want our item to change
  • We then created a new instance of CacheDependency class and pass this array as second parameter, the first parameter is for specifying file names array and is set to nothing in our example.
  • We then added an item with mykey key to the cache
Whenever the value of item with key myanotherkey is changed the item ith key mykey will be removed from the cache.

Removing items based on date and timespan

You can tell Cache object that you want to remove an item on some fixed date.
Cache.Insert("mykey", "myvalue", Nothing, 
DateTime.Today.AddDays(7), Nothing)
Here we added an item to cache with fixed date equal to today's date plus seven days. You can also specify that you want to remove an item after certain idle time.
Cache.Insert("mykey", "myvalue", Nothing, Nothing, 
New TimeSpan(12, 0, 0))
Here we added an item to cache that will expire if an item is not accessed for 12 hours. This is called as sliding expiration.

Setting item priority

As we have already discussed that when system resources became scarce ASP.NET will remove cached objects on its own. You may hint ASP.NET which items to be removed first than others. In other words you can set priority of cached items.
Cache.Insert("mykey", "myvalue", Nothing, Nothing, 
New TimeSpan(12, 0, 0), 
Caching.CacheItemPriority.High, Nothing)
Note how we used CacheItemPriority enum to specify that this item is having high priority.

Receiving notification when item is removed

In this final section we will see how to receive a notification when an item is removed from the cache.
Dim mycallback As New 
Caching.CacheItemRemovedCallback(AddressOf NotifyMe)

Cache.Insert("mykey", "myvalue", Nothing, Nothing, 
New TimeSpan(12, 0, 0), 
Caching.CacheItemPriority.High, mycallback)

Public Sub NotifyMe(ByVal key As String, ByVal value As Object, 
ByVal reason As Caching.CacheItemRemovedReason)
Select Case reason
	Case Caching.CacheItemRemovedReason.DependencyChanged
	Case Caching.CacheItemRemovedReason.Expired
	Case Caching.CacheItemRemovedReason.Removed
	Case Caching.CacheItemRemovedReason.Underused
End Select
End Sub
When an item is removed from the cache we can receive a notification by supplying a callback method of type CacheItemRemovedCallback. The signature of the method must match as that of NotifyMe in above example (name can be any valid method name). As the signature tells you, it receives item key, item value and reason due to which the item has been removed as parameters. You may use this method to perform some custom processing.


Caching is a very powerful feature of SP.NET. This article explained you various methods of caching and removing cached object. It also explained how to set dependencies between cached items and disk files, other items and datetime.

Bipin Joshi is an independent software consultant and trainer by profession specializing in Microsoft web development technologies. Having embraced the Yoga way of life he is also a meditation teacher and spiritual guide to his students. He is a prolific author and writes regularly about software development and yoga on his websites. He is programming, meditating, writing, and teaching for over 27 years. To know more about his ASP.NET online courses go here. More details about his Kriya and Meditation online course are available here.

Posted On : 05 October 2002

Tags : ASP.NET Web Forms Performance