Tuesday, August 14, 2007

ASP.NET 2.0: CacheKeyDependency

During the development of Issue Tracker ( http://www.ikosoftware.com/ ) , I had a lot of problems with CacheKeyDependency. It simply didn't work. The documentation in MSDN is definitely lacking. I couldn't find any good information on the internet either.

After a lot of trial and error attempts I finally made it work. Let's go through the following code to demonstrate the technique.

Add DataSource objects to the page.
Enable cache for the DataSource object:

.... asp:sqldatasource runat="server" CacheKeyDependency="MyTestKey"....

In code behind check Cache[CacheKeyDependency]. If it does not exists, create it:


 

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //create CacheKeyDependency if it does not exists
            if (Cache[SqlDataSource1.CacheKeyDependency] == null)
            {
                Cache[SqlDataSource1.CacheKeyDependency] = new object();
            }
        }
    }




To refresh the cache use the following code:



 Cache[SqlDataSource1.CacheKeyDependency] = new object(); 
 
 
 


You can have one CacheKeyDependency key word for multiple DataSource objects, so when you run

Cache["MyTestKey"] = new object();  
 
all the DataSource objects will have to renew the cache.


Hope it helps.

7 comments:

Anonymous said...

Thanks for posting, I wasn't able to find any useful documentation on the CacheKeyDependency either. In my experience I've had to use Cache.Remove("MyTestKey") to reset the data source cache.

MiniDrivingGeek said...

Cheers! Exactly what I was looking for!

Anonymous said...

Thanks, that helped me a lot!

Cheers
Vlad

Anonymous said...

Thanks my friend!
I was sending a plain string to the CachekKeyDependency but it wasn't doing the trick.

After reading your article I learned I was missing adding the same string to the application cache with the Cache class.

Thanks a lot man :)

Anonymous said...

Thanks for posting this. It was a realy help.

Dries Hoebeke said...

that seriously helped me out! thanks a lot mate

Ubaid R. Baig said...

Thanks a lot, exactly what I was looking for!!!