Showing posts with label CacheKeyDependency. Show all posts
Showing posts with label CacheKeyDependency. Show all posts

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.