多线程下使用HttpContext.Current.Cache.Get(key) 获取缓存时抛出null错误


多线程下使用HttpContext.Current.Cache.Get(key) 获取缓存时抛出null错误

解决办法如下:

 1   /// <summary>
 2         /// 获取缓存对象
 3         /// </summary>
 4         /// <param name="key">缓存Key</param>
 5         /// <returns>object对象</returns>
 6         public static object Get(string key)
 7         {
 8             if (string.IsNullOrEmpty(key))
 9             {
10                 return null;
11             }
12             //将HttpContext.Current.Cache.Get(key) 替换成HttpRuntime.Cache.Get(key) 在多线程下调取缓存的时候就不会抛NULL错误
13             return HttpRuntime.Cache.Get(key);
14         }

 

两者区别:

HttpRuntime.Cache是应用程序级别的, Web和非Web程序都可以使用.

HttpContext.Current.Cache是针对当前WEB上下文定义的,只能在wen程序下使用.

 

posted on 2016-04-05 18:48  菩提先生  阅读(1035)  评论(0编辑  收藏  举报

导航