The diary of your average web developer
27
Aug
2008
Posted under: Server Side
Tags:

A work colleague of mine made me aware of the rather useful CacheDependency class the other day and I’ve been implementing this in various places since. It is useful when you wish to store some data in an ASP.NET web application’s Cache but wish that data to remain in the Cache according to an external influence rather than a time frame.

For example, if you had a typed DataSet and stored some XML that conformed to its Schema on disk, you could use CacheDependency to store the data in the Cache until such time as the physical file is modified.

public static MyDataSet GetDataSet(string path)
{
  if (HttpContext.Current.Cache["MyDataSet" + path] == null)
  {
    MyDataSet ds = new MyDataSet();
    try
    {
      ds.ReadXml(HttpContext.Current.Server.MapPath(path));
    }
    catch (Exception ex)
    {
      throw new MyException(string.Format("Unable to load file '{0}' as a MyDataSet", path), ex);
    }
    CacheDependency dependency = new CacheDependency(HttpContext.Current.Server.MapPath(path));
    HttpContext.Current.Cache.Insert("MyDataSet" + path, ds, dependency);
  }
  return HttpContext.Current.Cache["MyDataSet" + path] as MyDataSet;
}

In the example above, when the file located at path is modified, the Cache will be cleared due to the dependency. When GetDataSet() is next called, the latest version of the file will be loaded into the Cache instead.

Share this post:
  • Facebook
  • del.icio.us
  • Digg
  • StumbleUpon
  • Technorati
  • Google
  • Reddit

No Comments

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment