缓存使用:记录缓存何时被移除

有些时候我们需要知道缓存被更新的频率,为此探究一下缓存的相关事件(CacheItemRemoveCallback)。下面是一个使用示例:
页面代码
        const string Key = "anystringtest";
        
const string path = @"/csdata/siteuser.xml";
        
private void Bind() {
            System.Web.Caching.Cache ocache 
= HttpRuntime.Cache;

            SiteUser user 
= ocache.Get(Key) as SiteUser;
            
if (user == null)
            {
                user 
= new SiteUser();
                user 
= user.DeSerializeFromXML(typeof(SiteUser), Server.MapPath(path)) as SiteUser;

                CacheDependency depend 
= new CacheDependency(
                    Server.MapPath(path));
                TimeSpan ts 
= TimeSpan.Zero;
                ocache.Insert(Key, user, depend,
                        DateTime.Now.AddMinutes(
3), ts, CacheItemPriority.Default,
                        
/***** 使用匿名委托 *****/
                        (
string key, object obj, CacheItemRemovedReason reason) => {
                            
string content = string.Format("{0} -  缓存移除. key={1}\r\n",
                                DateTime.Now, key);
                            file.Write(Server.MapPath(
"/csdata/log.txt"), content);
                        }
                        );
                lbldata.Text 
= "from cache";

            }
            lbluser.Text 
= user.NickName;
        }



原文地址:https://www.cnblogs.com/infozero/p/1623519.html