一,两个实现代码的差异:
我们用 .NET Reflector 看 HttpContext 类的 Cache 属性 ,会看到如下代码:
我们用 .NET Reflector 看 HttpContext 类的 Cache 属性 ,会看到如下代码:
public
Cache Cache
{ get { return HttpRuntime.Cache; } }
所以,两者在代码上是完全一致的。
二、两者的差异其实在于 HttpContext.Current
用 .NET Reflector 看 HttpContext.Current 如下:
public
static
HttpContext Current
{ get { return (ContextBase.Current as HttpContext); } }
ContextBase 类的静态属性 Current 如下:
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 返回 null 是因为
ContextBase.Current as HttpContext 这么一句,返回的 null 。
ContextBase.Current 是有值的,但是由于非 Web 应用,返回的 Object 无法转换为HttpContext,而返回 null 的。
ContextBase.Current as HttpContext 这么一句,返回的 null 。
ContextBase.Current 是有值的,但是由于非 Web 应用,返回的 Object 无法转换为HttpContext,而返回 null 的。
所以, HttpContext.Current.Cache 只可能用于 Web 应用的缓存。 而且是跟 HttpContext 紧密联系的。
三、HttpRuntime.Cache 可用于非 Web 应用的缓存。
比如我如下的一个控制台程序,是可以正常读写缓存的。而这里当然是不可以使用 HttpContext.Cache 的。
static
void
Main(
string
[] args)
{ System.Web.Caching.Cache c = System.Web.HttpRuntime.Cache; if (c != null) { c.Insert("1", "123141432432"); object o = c.Get("1"); Console.WriteLine(o); } Console.ReadLine(); }
总结,
1、HttpRuntime.Cache 相当于就是一个缓存具体实现类,这个类虽然被放在了 System.Web 命名空间下了。但是非 Web 应用也是可以拿来用的。
2、HttpContext.Cache 是对上述缓存类的封装,由于封装到了 HttpContext ,局限于只能在知道 HttpContext 下使用,即只能用于 Web 应用。
1、HttpRuntime.Cache 相当于就是一个缓存具体实现类,这个类虽然被放在了 System.Web 命名空间下了。但是非 Web 应用也是可以拿来用的。
2、HttpContext.Cache 是对上述缓存类的封装,由于封装到了 HttpContext ,局限于只能在知道 HttpContext 下使用,即只能用于 Web 应用。
综上所属,在可以的条件,尽量用 HttpRuntime.Cache ,而不是用 HttpContext.Cache 。
本文转自lidup 51CTO博客,原文链接:http://blog.51cto.com/lidup/218998,如需转载请自行联系原作者