Welcome 微信登录

首页 / 网页编程 / ASP.NET / USE HttpRuntime.Cache OVER HttpContext.Current.Cache

USE HttpRuntime.Cache OVER HttpContext.Current.Cache2011-11-04 博客园 Jun1st缓存是在ASP.NET开发中经常需要用到在技术,在使用过程中,通常会用到HttpRuntime.Cache和 HttpContext.Current.Cache。而且在使用过程中,通常会觉得这两个似乎用哪一个都行,都能达到缓存 数据的目的。那么这两个Cache到底有什么不同呢?在什么时候用哪一个比较好呢?这里谈谈我的一些了 解和看法吧。

两者的异同

先来看看msdn的解释

HttpContext.Cache : Gets the ASP.NET Cache object for the current request

HttpContext.Current : Gets the HttpContext object for the current request

从这个解释看,得到的Cache对象是当前请求的Cache对象。个人认为,这个解释有点误导性,会让 人误以为这时的Cache对象只是对于当前的Request的。而稍微想一下之后,就会发现这种理解是错误的。 如果Cache的内容只对当前的Request有用,那有何须缓存呢?

既然msdn得解释不行,那就直接看源代码吧,^_^,用Reflector打开HttpContext.Cache, 可以看到

public Cache Cache {       get       {             return HttpRuntime.Cache;       } }
从这代码可以看出,两者返回的都是是一样的。

难道这两者真的就完全一样吗?再来看看HttpContext.Current

public static HttpContext Current {       get       {             return (ContextBase.Current as HttpContext);       } }
ContextBase的源代码:

internal static object Current {       get       {             return CallContext.HostContext;       } }