CacheDependency in ASP.NET C#

In my previous articles, we learnt how to cache the data in Asp.Net. In this article, we discuss how we can cache the data based on some dependency using CacheDependency in Asp.Net C#. By CacheDependency, we can save data in cache until that particular dependency changes. If the Cache dependency changes then items in the cache get expires.

Open Microsoft Visual Studio 2015 => Create Asp.Net Web Application and name it as CacheDependencyExp. Add Employees.xml as shown below.

<?xml version="1.0" encoding="utf-8" ?>

<Employees>

  <Employee>

    <Id>1</Id>

    <Name>A</Name>

  </Employee>

  <Employee>

    <Id>2</Id>

    <Name>B</Name>

  </Employee>

  <Employee>

    <Id>3</Id>

    <Name>C</Name>

  </Employee>

  <Employee>

    <Id>4</Id>

    <Name>D</Name>

  </Employee>

</Employees>

Add C# code for WebForm1.aspx as shown below.

using System;

using System.Data;

using System.Web.Caching; 

namespace CacheDependencyExp

{

    public partial class WebForm1 : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {

            BindData();

        } 

        private void BindData()

        {

            if (Cache["Employees"] == null)

            {

                DataSet ds = new DataSet();

                ds.ReadXml(Server.MapPath("Employees.xml")); 

                Context.Cache.Insert("Employees", ds.Tables[0], new CacheDependency(Server.MapPath("Employees.xml")));

            } 

            gv1.DataSource = Cache["Employees"];

            gv1.DataBind();

        }

    }

}

As shown above every time we check whether Cache["Employees"] has data or not, if it contains data directly we are binding it to GridView gv1 else getting data from file into cache and binding it to gv1. While saving data in the cache, we are pointing CacheDependency to the XML file. That means whenever the data file changes, automatically Cache["Employees"] will get expires and fresh data from XML file will be in the cache.

Run the application; it displays Employees.xml data in GridView by saving in Cache. Try to refresh the page multiple times without modifying the file data and check whether data is coming from Cache, or it is fetching from the file. After the first call, every time gridview displays data from Cache. If you change the Employees.XML file content then automatically Cache will get expires, and data comes file.

                                                                                                                           CacheDependencyExp.zip