.net的文件依赖缓存,是指缓存内容依赖于某个文件的变更状态,一旦这个文件变更了,缓存内容则被清除失效。
下面这个例子,一旦html文件被改变,就向httpruntime.cache中insert一个新的数组:Cache.Insert("TimeNow", timestr, dep);
myCacheDependency.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="myCacheDependency.aspx.cs" Inherits="myCacheDependency" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>文件依赖缓存</title> </head> <body> <form id="form1" runat="server"> <div> </div> <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" /> <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> </form> </body> </html>
myCacheDependency.aspx.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.Caching; public partial class myCacheDependency : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { Label1.Text = DateTime.Now.ToString(); } } protected void Button1_Click(object sender, EventArgs e) { string timestr = Convert.ToString(HttpRuntime.Cache["TimeNow"]); if (String.IsNullOrEmpty(timestr)) { //如果获取失败,重载当前时间 timestr = DateTime.Now.ToString(); //新建缓存依赖 CacheDependency dep = new CacheDependency(Server.MapPath("./myPageCache.htm"),DateTime.Now); //插入缓存 Cache.Insert("TimeNow", timestr, dep); } //显示时间 Label1.Text = timestr; } }
myPageCache.htm (内容略)