ASP.NET - Cache Dependency

Asked By Mahesh B on 05-Jan-12 03:41 AM
Hi
can anyone give me example of cache dependency
Jitendra Faye replied to Mahesh B on 05-Jan-12 03:49 AM
ASP.NET allows you to use the http://msdn.microsoft.com/en-us/library/system.web.caching.sqlcachedependency.aspx class to create a cache item dependency on a table or row in a database. When a change occurs in the table or in a specific row, the item that has a dependency is invalidated and removed from the cache. You can set a dependency on a table in Microsoft SQL Server 7.0, SQL Server 2000, and SQL Server 2005. If you are using SQL Server 2005 you can also set a dependency on a specific record.

Using caching with a SQL dependency can dramatically increase application performance in certain scenarios.

For this you have to make following changes-

<!-- caching section group --> <caching> <sqlCacheDependency enabled = "true" pollTime = "1000" > <databases> <add name="Northwind" connectionStringName="NorthwindConnectionString1" pollTime = "1000" /> </databases> </sqlCacheDependency> </caching>


follow this link for example-

http://msdn.microsoft.com/en-us/library/ms178604.aspx
http://msdn.microsoft.com/en-us/library/e3w8402y.aspx
kalpana aparnathi replied to Mahesh B on 05-Jan-12 03:53 AM
hi,

// Insert the cache item.
CacheDependency dep = new CacheDependency(fileName, dt);
cache.Insert("key", "value", dep);
 
// Check whether CacheDependency.HasChanged is true.
if (dep.HasChanged)
  Response.Write("<p>The dependency has changed."); 
else Response.Write("<p>The dependency has not changed.");


Thanks,
Riley K replied to Mahesh B on 05-Jan-12 04:04 AM



Here is a simple example

protected void Page_Load(object sender, EventArgs e)
{      
  string fileContent = Cache["SampleFile"] as string;
  if (string.IsNullOrEmpty(fileContent))
  {
    using (StreamReader sr = File.OpenText(Server.MapPath("~/SampleFile.txt")))
     {
       fileContent = sr.ReadToEnd();
       Cache.Insert("SampleFile", fileContent, new System.Web.Caching.CacheDependency(Server.MapPath("~/SampleFile.txt")));
     }
  }  
  TextBox1.Text = fileContent;
}

the application checks the cache for an item in the cache named SampleFile and assigns the value to the fileContent variable.

Regards