浅析ASP.NET清空缓存时遇到的问题

在网站中要做一个清理缓存的功能(也就是在缓存为到期之前就强制缓存过期),程序中有的地方使用的HttpRuntime.Cache来做的缓存,而和数据库交互部分则使用ObjectDataSource提供的缓存机制。清理HttpRuntime.Cache的缓存很简单,只要

 
 
 
  1. List keys = new List();  
  2.             // retrieve application Cache enumerator  
  3. IDictionaryEnumerator enumerator = HttpRuntime.Cache.GetEnumerator();  
  4.             // copy all keys that currently exist in Cache  
  5.             while (enumerator.MoveNext())  
  6.             {  
  7.                 keys.Add(enumerator.Key.ToString());  
  8.             }  
  9.             // delete every key from cache  
  10.             for (int i = 0; i < keys.Count; i++)  
  11.             {  
  12.                 HttpRuntime.Cache.Remove(keys[i]);  
  13.             } 

就可以了。

本以为ObjectDataSource等数据源的缓存也是保存在HttpRuntime.Cache中,经过测试没想到竟然不是,因为执行上面的代码以后ObjectDataSource仍然是从缓存读取数据。

使用Reflector反编译发现ObjectDataSource是使用HttpRuntime.CacheInternal来实现的缓存,气氛呀,为什么微软总爱搞“特殊化”,对外提供一个Cache用,自己偷偷用CacheInternal做缓存。CacheInternal是internal的,因此没法直接写代码调用,同时CacheInternal中也没提供清空缓存的方法,只能通过实验发现_caches._entries是保存缓存的Hashtable,因此就用反射的方法调用CacheInternal,然后拿到_caches._entries,***clear才算ok。

最终代码如下:

 
 
 
  1. //HttpRuntime下的CacheInternal属性(Internal的,内存中是CacheMulti类型)是
  2. ObjectDataSource等DataSource保存缓存的管理器  
  3. //因为CacheInternal、_caches、_entries等都是internal或者private的,
  4. 所以只能通过反射调用,而且可能会随着.Net升级而失效  
  5.     object cacheIntern = CommonHelper.GetPropertyValue(typeof(HttpRuntime), "CacheInternal") as IEnumerable;  
  6.     //_caches是CacheMulti中保存多CacheSingle的一个IEnumerable字段。  
  7.     IEnumerable _caches = CommonHelper.GetFieldValue(cacheIntern, "_caches") as IEnumerable;  
  8.     foreach (object cacheSingle in _caches)  
  9.     {  
  10.         ClearCacheInternal(cacheSingle);  
  11.     }  
  12.  
  13. private static void ClearCacheInternal(object cacheSingle)  
  14. {  
  15.     //_entries是cacheSingle中保存缓存数据的一个private Hashtable  
  16.  Hashtable _entries = CommonHelper.GetFieldValue(cacheSingle, "_entries") as Hashtable;  
  17.     _entries.Clear();  
  18. }  
  19.  
  20. mary>  
  21. /// 得到type类型的静态属性propertyName的值  
  22. ///   
  23. ///   
  24. ///   
  25. ///   
  26. public static object GetPropertyValue(Type type, string propertyName)  
  27. {  
  28.     foreach (PropertyInfo rInfo in type.GetProperties
  29. (BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Public | BindingFlags.Instance))  
  30.     {  
  31.         if (rInfo.Name == propertyName)  
  32.         {  
  33.             return rInfo.GetValue(null, new object[0]);  
  34.         }  
  35.     }  
  36.     throw new Exception("无法找到属性:" + propertyName);  
  37. }  
  38.  
  39. ///   
  40. /// 得到object对象的propertyName属性的值  
  41. ///   
  42. ///   
  43. ///   
  44. ///   
  45. public static object GetPropertyValue(object obj, string propertyName)  
  46. {  
  47.     Type type = obj.GetType();  
  48.     foreach (PropertyInfo rInfo in type.GetProperties
  49. (BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Public | BindingFlags.Instance))  
  50.     {  
  51.         if (rInfo.Name == propertyName)  
  52.         {  
  53.             return rInfo.GetValue(obj, new object[0]);  
  54.         }  
  55.     }  
  56.     throw new Exception("无法找到属性:" + propertyName);  
  57. }  
  58.  
  59. public static object GetFieldValue(object obj, string fieldName)  
  60. {  
  61.     Type type = obj.GetType();  
  62.     foreach (FieldInfo rInfo in type.GetFields
  63. (BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Public | BindingFlags.Instance))  
  64.     {  
  65.         if (rInfo.Name == fieldName)  
  66.         {  
  67.             return rInfo.GetValue(obj);  
  68.         }  
  69.     }  
  70.     throw new Exception("无法找到字段:" + fieldName);  

上面方法由于是通过crack的方法进行调用,可能有潜在的问题,因此仅供参考。

在google上搜索到另外一篇文章 http://www.msdnkk.hu/Articles/Clear_OutputCache-Minden_oldal_torlese ,由于是匈牙利文的,也看不懂在说什么,不过主干是代码,看他代码的思路和我一样,贴过来也供参考

 

 
 
 
  1. private void clearOutputCache()  
  2. {  
  3.     Type ct = this.Cache.GetType();  
  4.     FieldInfo cif = ct.GetField( "_cacheInternal", BindingFlags.NonPublic | BindingFlags.Instance );  
  5.     Type cmt = Cache.GetType().Assembly.GetType( "System.Web.Caching.CacheMultiple" );  
  6.     Type cachekeyType = Cache.GetType().Assembly.GetType( "System.Web.Caching.CacheKey" );  
  7.     FieldInfo cachesfield = cmt.GetField( "_caches", BindingFlags.NonPublic | BindingFlags.Instance );  
  8.  
  9.     object cacheInternal = cif.GetValue( this.Cache );  
  10.     object caches = cachesfield.GetValue( cacheInternal );  
  11.  
  12.     Type arrayType = typeof( Array );  
  13.     MethodInfo arrayGetter = arrayType.GetMethod( "GetValue", new Type[] { typeof( int ) } );  
  14.     object cacheSingle = arrayGetter.Invoke( caches, new object[] { 1 } );  
  15.  
  16.     FieldInfo entriesField = cacheSingle.GetType().GetField( "_entries", BindingFlags.Instance | BindingFlags.NonPublic );  
  17.     Hashtable entries = (Hashtable) entriesField.GetValue( cacheSingle );  
  18.  
  19.     List keys = new List();  
  20.     foreach( object o in entries.Keys )  
  21.     {  
  22.         keys.Add( o );  
  23.     }  
  24.  
  25.     MethodInfo remove = cacheInternal.GetType().GetMethod( "Remove", BindingFlags.NonPublic | BindingFlags.Instance, null,  
  26.         new Type[] { cachekeyType, typeof( CacheItemRemovedReason ) }, null );  
  27.     foreach( object key in keys )  
  28.     {  
  29.         remove.Invoke( cacheInternal, new object[] { key, CacheItemRemovedReason.Removed } );  
  30.     }  
  31. 原文标题:清除ASP.Net缓存

    链接:http://www.cnblogs.com/rupeng/archive/2010/08/05/1793499.html

    【编辑推荐】

    1. 详解ASP.NET缓存的工作原理
    2. ASP.NET缓存数据技巧三则
    3. 再谈ASP.NET缓存机制:开发效率与优化的平衡
    4. .NET分布式缓存之Memcached执行速度检测
    5. 如何避免ASP.NET缓存占用系统资源

    网站栏目:浅析ASP.NET清空缓存时遇到的问题
    文章源于:http://www.shufengxianlan.com/qtweb/news5/435405.html

    网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

    广告

    声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联