Monday, July 23, 2007

Asp.net Cache

Sharing some gyan on the asp.net cache.There are many ways we can maintain state in asp.net and cache is the coolest of all.The main advantage with cache object is that it is specific to single user,subset of users or even all users.It is really very flexible,versatile and performance is better.The cache object can be used both declaratively and programmatically.Adding and deleting data to the cache is very easy.
I will use the insert method because it supports several overloads dependencies, timeouts, priority, and callbacks.
// Add to cache
Cache["testKey"] = "Promothash";

// Read from cache
Response.Write(Cache["testKey"]);

// to add and set duration of cache to 5 seconds
Cache.Insert("testKey","Promothash", null, System.DateTime.Now.AddSeconds(5),
System.Web.Caching.Cache.NoSlidingExpiration);


It can accept one more argument i.e callback function can be excuted when the
cache expires.Create a delegate of the callback function and call it.

//instance of the callback delegate
Callbackcache callBack = new Callbackcache (obj);