This blog is moved to
http://amalhashim.wordpress.com

Tuesday, June 17, 2008

ASP.Net Caching

We can easily cache data in asp.net using the Caching class provided by asp.net

Here is an example of how to cache data.

if(Cache["data"]==null)
{
Cache.Insert("data", data, null, System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration);
}

This will cache the "data" until it is removed from the memory.

So how can we know when the cached data is being removed from the memory?

ASP.Net provides a cool feature, that enables us to do it.

There is a delegate to achieve this
System.Web.Caching.CacheItemRemovedCallback
which has the following signature

void RemoveCacheItemHandler(string key, Object value, CacheItemRemovedReason reason);

This delegate can be used to get notification once a particular cached item being removed.

Example of how we can use the delegate:

if(Cache["data"]==null)
{
Cache.Insert("data", data, null, System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration, RemoveCacheItemHandler);
}

public void RemovedCacheItemHandler(string key, Object value, CacheItemRemovedReason reason)
{
switch (key)
{
case "data":
// cache has been removed; do the process
break;
}
}

No comments: