Friday, September 26, 2008

CacheItemRemovedCallback and asynchronous programming model for ASP.NET Cache

ASP.NET has a very good asynchronous programming model that uses the CacheItemRemovedCallback delegate to inform the application when a cache item is expired and helps the developer to write code to retrieve it.

The CacheItemRemovedCallback is defined as
public delegate void CacheItemRemovedCallback(string key, object value, CacheItemRemovedReason reason);

To explain the concept I will use the following classes which have a parent – child relationship.

public class User

{

public Int32 ID { get; set; }

public String Name { get; set; }

}

public class Details

{

public User User { get; set; }

public Int32 Extension { get; set; }

public String Project { get; set; }

}

You can instantiate and initialize the objects in your code like

User parent = new User { Name = "Me", ID = 1 };

Details child = new Details {User = parent, Project = "My Project", Extension = 555 };

And later when adding the objects into Cache you create the dependencies and the callback function reference for the child data as follows.

Insert parent object and create CacheDependency.

Cache.Insert("Parent", parent);

CacheDependency dependency = new CacheDependency(null, new String[] { " Parent" });


Insert child object and add a CacheItemRemovedCallback delegate.

Cache.Insert(

"Child",

child,

dependency,

DateTime.Now.AddHours(30),

TimeSpan.Zero,

CacheItemPriority.Normal,

new CacheItemRemovedCallback(

delegate(String key, Object value, CacheItemRemovedReason reason)

{

if(reason == CacheItemRemovedReason.DependencyChanged)

//Use AJAX/ events here if required.

Cache.Insert(key, new Details { User = null, Extension = default(Int32), Project = String.Empty });

})

);

Now whenever the parent object is removed from the cache the anonymous method gets called and you can do an appropriate action based on the design.

No comments: