1 如果使用cache的add方法或者接受CacheItemPriority值得Insert方法重载接收通知,可以提供CacheItemRemovedCallBack对象,选择在清除对象时接收通知
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; namespace Cachting { public partial class Default : System.Web.UI.Page { private static readonly string CACHE_KEY = "codebehind_ts"; protected void Page_Load(object sender, EventArgs e) { } public string GetTime() { string ts = (string)Cache[CACHE_KEY]; if (ts==null) { Cache[CACHE_KEY]=ts= DateTime.Now.ToLongTimeString(); Cache.Insert(CACHE_KEY, ts, null, Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(10), System.Web.Caching.CacheItemPriority.Normal, HandleRemoveNotification); } else { ts += "<b>(Cached)</b>"; } return ts; } private void HandleRemoveNotification(string key, object value, CacheItemRemovedReason reason) { string cacheData = (string)Cache[CACHE_KEY]; cacheData = cacheData + "10 秒之后的清楚缓存数据的通知"; Response.Write("<Script Language='JavaScript'>window.alert('" + cacheData.ToString() + "');</script>"); } } }
示例代码如上