1、httpruntime.cache 相当于就是一个缓存具体实现类,这个类虽然被放在了 system.web 命名空间下了。但是非 web 应用也是可以拿来用的。

2、httpcontext.cache 是对上述缓存类的封装,由于封装到了 httpcontext ,局限于只能在知道 httpcontext 下使用,即只能用于 web 应用。

综上所属,在可以的条件,尽量用 httpruntime.cache ,而不是用 httpcontext.cache 。 

cache有以下几条缓存数据的规则。
第一,数据可能会被频繁的被使用,这种数据可以缓存。
第二,数据的访问频率非常高,或者一个数据的访问频率不高,但是它的生存周期很长,这样的数据最好也缓存起来。
第三是一个常常被忽略的问题,有时候我们缓存了太多数据,通常在一台x86的机子上,如果你要缓存的数据超过800m的话,就会出现内存溢出的错误。所以说缓存是有限的。换名话说,你应该估计缓存集的大小,把缓存集的大小限制在10以内,否则它可能会出问题。

1.cache的创建
   cache.insert(string key,object value,cachedependency dependencies,datetime absoluteexpiration,timespan slidingexpiration)//只介绍有5个参数的情况,其实cache里有很几种重载
参数一:引用该对象的缓存键
参数二:要插入缓存中的对象
参数三:缓存键的依赖项,当任何依赖项更改时,该对象即无效,并从缓存中移除。 null.”>如果没有依赖项,则此参数包含 null。
参数四:设置缓存过期时间
参数五:参数四的依赖项,如果使用绝对到期,null.”>slidingexpiration parameter must benoslidingexpiration.”>则 slidingexpiration 参数必须为 
noslidingexpiration

2.销毁cache
cache.remove(string key)//key为缓存键,通过缓存键进行销毁
3.调用cache
例如你存的是一个datatable对象,调用如下: datatable finaltable = cache[“dt”] as datatable;
4.一般什么时候选用cache
cache一般用于数据较固定,访问较频繁的地方,例如在前端进行分页的时候,初始化把数据放入缓存中,然后每次分页都从缓存中取数据,这样减少了连接数据库的次数,提高了系统的性能。

    /// <summary>  
    /// 获取数据缓存  
    /// </summary>  
    /// <param name="cachekey">键</param>  
    public static object getcache(string cachekey)  
    {  
        var objcache = httpruntime.cache.get(cachekey);  
        return objcache;  
    }  
    /// <summary>  
    /// 设置数据缓存  
    /// </summary>  
    public static void setcache(string cachekey, object objobject)  
    {  
        var objcache = httpruntime.cache;  
        objcache.insert(cachekey, objobject);  
    }  
    /// <summary>  
    /// 设置数据缓存  
    /// </summary>  
    public static void setcache(string cachekey, object objobject, int timeout = 7200)  
    {  
        try  
        {  
            if (objobject == null) return;  
            var objcache = httpruntime.cache;  
            //相对过期  
            //objcache.insert(cachekey, objobject, null, datetime.maxvalue, timeout, cacheitempriority.notremovable, null);  
            //绝对过期时间  
            objcache.insert(cachekey, objobject, null, datetime.now.addseconds(timeout), timespan.zero, cacheitempriority.high, null);  
        }  
        catch (exception)  
        {  
            //throw;  
        }  
    }  
    /// <summary>  
    /// 移除指定数据缓存  
    /// </summary>  
    public static void removeallcache(string cachekey)  
    {  
        var cache = httpruntime.cache;  
        cache.remove(cachekey);  
    }  
    /// <summary>  
    /// 移除全部缓存  
    /// </summary>  
    public static void removeallcache()  
    {  
        var cache = httpruntime.cache;  
        var cacheenum = cache.getenumerator();  
        while (cacheenum.movenext())  
        {  
            cache.remove(cacheenum.key.tostring());  
        }  
    }