学习和分享一点简单的System.Web.HttpRuntime.Cache的使用经验

配置文件

< appSettings >
  
< add key = " EnableCache "  value = " true " />
  
< add key = " CacheDurationSeconds "  value = " 300 " />
</ appSettings >

操作方法

 

ExpandedBlockStart.gif 代码
using  System;
using  System.Web.Configuration;

public   class  SiteHelper
{
    
static   public   object  GetCache( string  CacheId)
    {
        
object  objCache  =  System.Web.HttpRuntime.Cache.Get(CacheId);

        
//  判斷 Cache 是否啟用
         if  (WebConfigurationManager.AppSettings[ " EnableCache " ==   null
            
||   ! Convert.ToBoolean(WebConfigurationManager.AppSettings[ " EnableCache " ]))
        {
            objCache 
=   null ;
            System.Web.HttpRuntime.Cache.Remove(CacheId);
        }

        
return  objCache;
    }

    
///   <summary>
    
///  寫入 Cache 資料 ( 預設 60 秒 )
    
///   </summary>
    
///   <param name="CacheId"></param>
    
///   <param name="objCache"></param>
     static   public   void  SetCache( string  CacheId,  object  objCache)
    {
        
if  (WebConfigurationManager.AppSettings[ " CacheDurationSeconds " !=   null )
        {
            SetCache(CacheId, objCache, 
                Convert.ToInt32(WebConfigurationManager.AppSettings[
" CacheDurationSeconds " ]));
        }
        
else
        {
            SetCache(CacheId, objCache, 
60 );
        }
    }

    
static   public   void  SetCache( string  CacheId,  object  objCache,  int  cacheDurationSeconds)
    {
        
if  (objCache  !=   null )
        {
            System.Web.HttpRuntime.Cache.Insert(
                CacheId,
                objCache,
                
null ,
                System.Web.Caching.Cache.NoAbsoluteExpiration,
                
new  TimeSpan( 0 0 , cacheDurationSeconds),
                System.Web.Caching.CacheItemPriority.High,
                
null );
        }
    }
}

使用方法

ExpandedBlockStart.gif 代码
string  strCache1  =  SiteHelper.GetCache( " Cache1 " as   string ;

if  (strCache1  ==   null )
{
    Response.Write(
" <p>Cache is empty</p> " );

    strCache1 
=   " OK " ;
    SiteHelper.SetCache(
" Cache1 " , strCache1,  30 );
}

Response.Write(strCache1);

 常见问题#Cache显示与清空问题

ExpandedBlockStart.gif 代码
List < string >  cacheKeys  =   new  List < string > ();
IDictionaryEnumerator cacheEnum 
=  Cache.GetEnumerator();
while  (cacheEnum.MoveNext())
{
    cacheKeys.Add(cacheEnum.Key.ToString());
}
foreach  ( string  cacheKey  in  cacheKeys)
{
    Cache.Remove(cacheKey);
}
ExpandedBlockStart.gif 代码
     // 清除所有缓存
     protected   void  RemoveAllCache()
    {
        System.Web.Caching.Cache _cache 
=  HttpRuntime.Cache;
        IDictionaryEnumerator CacheEnum 
=  _cache.GetEnumerator();
        ArrayList al 
=   new  ArrayList();
        
while  (CacheEnum.MoveNext())
        {
            al.Add(CacheEnum.Key);
        }
        
foreach  ( string  key  in  al)
        {
            _cache.Remove(key);
        }
        show();
    }
    
// 显示所有缓存 
     void  show()
    {
        
string  str  =   "" ;
        IDictionaryEnumerator CacheEnum 
=  HttpRuntime.Cache.GetEnumerator();

        
while  (CacheEnum.MoveNext())
        {
            str 
+=   " 缓存名<b>[ "   +  CacheEnum.Key  +   " ]</b><br /> " ;
        }
        
this .Label1.Text  =   " 当前网站总缓存数: "   +  HttpRuntime.Cache.Count  +   " <br /> "   +  str;
    }

添加到扩展方法

ExpandedBlockStart.gif 代码
using  System;
using  System.Web.Caching;
using  System.Collections;
using  System.Collections.Generic;

///   <summary>
///  擴充 System.Web.Caching 命名空間的 Extension Methods
///   </summary>
static   public   class  CacheExtensionMethod
{
    
public   static   void  Clear( this  Cache x)
    {
        List
< string >  cacheKeys  =   new  List < string > ();
        IDictionaryEnumerator cacheEnum 
=  x.GetEnumerator();
        
while  (cacheEnum.MoveNext())
        {
            cacheKeys.Add(cacheEnum.Key.ToString());
        }
        
foreach  ( string  cacheKey  in  cacheKeys)
        {
            x.Remove(cacheKey);
        }
    }
}

MSDN

C# 语言的 foreach 语句(在 Visual Basic 中为 for each)隐藏了枚举数的复杂性。因此,建议使用 foreach,而不直接操作枚举数。

枚举数可用于读取集合中的数据,但不能用于修改基础集合。

最初,枚举数定位在集合中第一个元素前。Reset 方法还会将枚举数返回到此位置。在此位置,调用 Current 属性会引发异常。因此,在读取 Current 的值之前,必须调用 MoveNext 方法将枚举数提前到集合的第一个元素。

在调用 MoveNextReset 之前,Current 返回同一个对象。MoveNextCurrent 设置为下一个元素。

如果 MoveNext 越过集合的末尾,则枚举数将放置在集合中最后一个元素的后面,而且 MoveNext 返回 false。当枚举数位于此位置时,对 MoveNext 的后续调用也返回 false。如果最后一次调用 MoveNext 返回 false,则调用 Current 会引发异常。若要再次将 Current 设置为集合的第一个元素,可以调用 Reset,然后再调用 MoveNext

只要该集合保持不变,枚举数也就保持有效。如果对集合进行了更改(如添加、修改或删除元素),则枚举数将失效且不可恢复,并且下一次对 MoveNextReset 的调用将引发 InvalidOperationException。如果在 MoveNextCurrent 之间修改集合,那么即使枚举数已经无效,Current 也将返回它所设置成的元素。

枚举数没有对集合的独占访问权;因此,从头到尾对一个集合进行枚举在本质上不是一个线程安全的过程。即使某个集合已同步,其他线程仍可以修改该集合,这会导致枚举数引发异常。若要在枚举过程中保证线程安全,可以在整个枚举过程中锁定集合,或者捕捉由于其他线程进行的更改而引发的异常。

 

大中型Cache应用推荐:Velocity,memcached等

转载于:https://www.cnblogs.com/leeolevis/archive/2010/02/02/1662283.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值