Cache对象中常用方法的理解

1、ASP.NET中调用Cache的方法 

   1):HttpRuntime.Cache; 

   2):Page.Cache; 

   3:)HttpContext.Current.Cache; 自己感觉三者差不多

2、功能:缓存服务器上常用数据;存储任意数据对象(如哈希表和数据集)的词典;有两种过期策略选择(绝对过期(DateTime)和弹性过期(TimeSpan));缓存优先级(CacheItemPriority枚举);可以使用缓存依赖(CacheDependency的实例。添加依赖于其他文件或缓存项的对象,并在从 Cache 中移除对象时执行回调以通知应用程序。)

3、Cache.Add方法:使用cache集合中已有的Key值添加,会抛出异常

   Cache.Insert方法:添加相同的Key值,会更改该key值的value,不会抛出异常,个人比较喜欢用这个方法。呵呵

  上述两个添加缓存的方法都具有依赖项、过期和优先级策略以及一个委托(可用于在从 Cache 移除插入项时通知应用程序);

  Cache.get 和Cache.Item:通过相应的key值获取缓存。

4、过期策略。注意两种过期策略只能使用其中一种,使用了NoAbsoluteExpiration 参数就得把NoSlidingExpiration参数置为TimeSpan.Zero,使用了NoSlidingExpiration参数就得把NoAbsoluteExpiration 参数置为 DateTime.MaxValues,

  1):绝对过期 NoAbsoluteExpiration 。一般使用DateTime.Now.AddDay(10)形式添加,例如:

    Cache.Insert("Data", ds,null, DateTime.Now.AddSeconds(10), TimeSpan.Zero);  TimeSpan.Zero表示不适用弹性过期策略,不管使用是否,过十秒就过期

  2):弹性过期 NoSlidingExpiration

    Cache.Insert("Data", ds, null, DateTime.MaxValue, TimeSpan.FromSeconds(10));  DateTime.MaxValue表示不使用绝对过期策略,缓存连续十秒没人使用就过期

5、CacheDependency对象。向缓存添加一个依赖于另一个对象(如文件或文件数组)的项,则在该对象更改时会自动从缓存中移除该依赖项。

 CacheDependency depend = new CacheDependency("c://1.xml",DateTime.Now);//设置缓存依赖对象           
 HttpRuntime.Cache.Insert("1", "cache", depend, DateTime.Now.AddDays(1),TimeSpan.Zero,CacheItemPriority.High,null);//插入缓存                      
 if (depend.HasChanged)//依赖文件1://1.xml是否修改            
{               
   Response.Write("缓存已经被清空!");         
 }

  


 

posted on 2011-11-09 22:22  kobeycs  阅读(845)  评论(0编辑  收藏  举报

导航