.Net Cache

在.net中有两个类实现了Cache

  • HttpRuntime.Cache 应该程序使用的Cache,web也可以用
  • HttpContext.Current.Cache  web上下文的Cache对象,只能在Web上使用

 

asp.net 页面缓存的封装

  /// <summary>
        /// 根据 cacheKey 获取缓存内容
        /// </summary>
        /// <param name="context">HttpContext</param>
        /// <param name="cacheName">key</param>
        /// <param name="cacheFunc">Func委托,该方法返回结果为要缓存的对象,当存在改缓存时,不会执行该委托的方法</param>
        /// <param name="timeoutHours">单位:小时,默认值为12</param>
        /// <returns>缓存内容</returns>
        public static Object GetCacheByName(HttpContextBase context,string cacheName,Func<object>cacheFunc,int timeoutHours=12)
        {
            if (context.Cache[cacheName] == null)
            {
                context.Cache.Insert(cacheName, cacheFunc.Invoke(), null, DateTime.Now.AddHours(timeoutHours), Cache.NoSlidingExpiration);
            }
            return context.Cache[cacheName];
        }
View Code

 

posted @ 2017-03-02 22:30  WangwangJie  阅读(132)  评论(0编辑  收藏  举报