CacheDependency is an important part in pet shop 4.0.
Here is some example code on how to use CacheDependency
1. create a new xml file as following:
1 2 3 4 5 6 7 8 9 10 11 | <?xml version="1.0"?> <bookstore> <book> <title>ado.net tutorial</title> <author>wudi</author> </book> <book> <title>ado.net tutorial</title> <author>wudi</author> </book> </bookstore> |
2. create a new webform page running
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | public partial class Index : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { GetData(); } } private void GetData() { DataTable source = new DataTable(); if (Cache["data"] == null) { DataSet ds = new DataSet(); ds.ReadXml(Server.MapPath("bookstore.xml")); Response.Write("<p>" + ds.Tables[0].Rows.Count + "</p>"); source = ds.Tables[0]; CacheDependency cdy = new CacheDependency(Server.MapPath("bookstore.xml")); Cache.Insert("data", source, cdy); if (cdy.HasChanged) { System.Diagnostics.Debug.WriteLine("Xml Has changed!!!!"); } } else { source = Cache["data"] as DataTable; } GridView1.DataSource = source; GridView1.DataBind(); } |
3. Try to change bookstore.xml, then you will find cache is null , then the cache will be reloaded.
Sometime, one cache may depends on multiple dependency.
The following example show one cache depends on two xml files “ProductList1.xml” and “ProductList2.xml”
1 2 3 4 5 6 7 8 9 10 | CacheDependency dep1 = new CacheDependency( Server.MapPath("ProductList1.xml")); CacheDependency dep2 = new CacheDependency( Server.MapPath("ProductList2.xml")); // Create the aggregate. CacheDependency[] dependencies = new CacheDependency[]{dep1, dep2}; AggregateCacheDependency aggregateDep = new AggregateCacheDependency(); aggregateDep.Add(dependencies); // Add the dependent cache item. Cache.Insert("ProductInfo", prodInfo, aggregateDep); |