January 2018 : Instructor-led Online Course in ASP.NET Core 2.0. Conducted by Bipin Joshi. Read more...
Registration for January 2018 batch of ASP.NET Core 2.0 instructor-led online course has already started. Conducted by Bipin Joshi. Register today ! Click here for more details.

<%@ Page %>

Caching Techniques In ASP.NET - Part II

Introduction

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(emp.Name)
Else
	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(emp.Name)
Else
	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.
Cache.Remove("myemp")

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()
	sr.Close()
	Cache.Insert("mycatalog", strcatalog, New 
	Caching.CacheDependency(Server.MapPath("catalog.htm")))
End If
Response.Write(Cache("mycatalog"))
Here,
  • 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
Response.Write(Cache("mykey"))
Here,
  • 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.

Summary

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 a software consultant, an author and a yoga mentor having 22+ years of experience in software development. He also conducts online courses in ASP.NET MVC / Core and Design Patterns. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced the Yoga way of life he also teaches Meditation and Mindfulness to interested individuals. To know more about him click here.

Get connected : Twitter  Facebook  Google+  LinkedIn

Posted On : 05 October 2002


Tags : ASP.NET Web Forms Performance