代码改变世界

USE HttpRuntime.Cache OVER HttpContext.Current.Cache

2009-05-13 15:51  Jun1st  阅读(2270)  评论(6编辑  收藏  举报

 

缓存是在ASP.NET开发中经常需要用到在技术,在使用过程中,通常会用到HttpRuntime.CacheHttpContext.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;
      }
}

再接着看CallContext.HostContext

public static object HostContext
{
      get
      {
            IllogicalCallContext context1 = Thread.CurrentThread.GetIllogicalCallContext();
            object obj1 = context1.HostContext;
            if (obj1 == null)
            {
                  LogicalCallContext context2 = CallContext.GetLogicalCallContext();
                  obj1 = context2.HostContext;
            }
            return obj1;
      }
}

从这三段代码中可以看出,对于Web项目来说,通过HttpContext.Current.Cache来访问Cache存在着几乎可以忽略不计的类型转换过程。而对于非Web项目来说,将ContextBase.Current转换为HttpContext就会返回null。除此之外,调用HttpContext还需要一些而外的查找工作,需要解析当前正在运行的的线程和当前的context。不过,个人认为这点小小的额外的工作应该不会带来什么性能问题。

HttpRuntime.Cache可以用在非Web项目中

这听起来有点怪怪的,呵呵,HttpRuntime的Cache居然可以用在非Web项目中。但是事实正是如此,需要做的只不过是把System.Web这个dll加到我们项目中来就好了。有兴趣的朋友可以看看这个Using the ASP.NET Cache outside of ASP.NET

 

总结,using HttpRuntime.Cache overHttpContext.Current.Cache