asp.net 自动检测缓存内容是否变化
1 使用cache.Insert方法时,新建一个System.Web.Caching.CacheDependency对象,告诉缓存,当缓存的内容发生变化时,将删除缓存,并重新缓存
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.IO; namespace Cachting { public class CityListInfo { public string Timestamp { get; set; } public string Html { get; set; } } public partial class CitiesControl : System.Web.UI.UserControl { private static readonly string fileName = "/CitiesList.html"; private static readonly string CACHE_KEY = "cities_html"; private CityListInfo cityInfo; private bool cached = false; protected void Page_Load(object sender, EventArgs e) { cityInfo = Cache[CACHE_KEY] as CityListInfo; if (cityInfo==null) { cityInfo = new CityListInfo { Timestamp=DateTime.Now.ToLongTimeString(), Html =File.ReadAllText(MapPath(fileName))}; //只要未修改文件就应该缓存数据 Cache.Insert(CACHE_KEY, cityInfo,new System.Web.Caching.CacheDependency(MapPath(fileName))); } else { cached = true; } } public string GetCities() { //return File.ReadAllText(MapPath(fileName)); return cityInfo.Html; } public string GetTimeStamp() { // return DateTime.Now.ToLongTimeString(); return cityInfo.Timestamp + (cached ? "<b>Cached</b>" : ""); } } }