Monday, August 30, 2010

Cache API

Imagine a situation where you want to load data from an XML file and you want to avoid redundant IO operation by caching the data and invalidate cache if the file changes. To do the job, you can use a CacheDependency object and pass in the path to the file to the constructor. Here is the complete code:

DataSet ds = null;
ds = (DataSet)Cache["_records"];
if (ds == null)
{
      string path = Server.MapPath("records.xml");
      ds = new DataSet();
      ds.ReadXml(path);
      CacheDependency cd = new CacheDependency(path);
      Cache.Insert("_records", ds, cd);
}
GridView1.DataSource = ds;
GridView1.DataBind();

The codes checks if the cache already contains the data. If not, it refers to the file and loads the data and inserts it into the cache. Then it is displayed in a GridView control.

In order to remove the cache programmatically, you can use this code:

Cache.Remove("_records");

No comments:

Post a Comment