HttpRuntime.cache

简介:
一,两个实现代码的差异:
我们用 .NET Reflector  看 HttpContext 类的 Cache 属性 ,会看到如下代码:

 
None.gif public Cache Cache ExpandedBlockStart.gif { InBlock.gifget ExpandedSubBlockStart.gif{ InBlock.gifreturn HttpRuntime.Cache; ExpandedSubBlockEnd.gif } ExpandedBlockEnd.gif}
所以,两者在代码上是完全一致的。

二、两者的差异其实在于 HttpContext.Current
用 .NET Reflector  看 HttpContext.Current 如下:
 
None.gif public static HttpContext Current ExpandedBlockStart.gif { InBlock.gifget ExpandedSubBlockStart.gif{ InBlock.gifreturn (ContextBase.Current as HttpContext); ExpandedSubBlockEnd.gif } ExpandedBlockEnd.gif}
ContextBase 类的静态属性  Current 如下:
 
None.gif internal static object Current ExpandedBlockStart.gif { InBlock.gifget ExpandedSubBlockStart.gif{ InBlock.gifreturn CallContext.HostContext; ExpandedSubBlockEnd.gif } ExpandedBlockEnd.gif}

CallContext 类的静态属性 HostContext 如下:
 
None.gif public static object HostContext ExpandedBlockStart.gif { InBlock.gifget ExpandedSubBlockStart.gif{ InBlock.gif IllogicalCallContext context1 = Thread.CurrentThread.GetIllogicalCallContext(); InBlock.gifobject obj1 = context1.HostContext; InBlock.gifif (obj1 == null) ExpandedSubBlockStart.gif{ InBlock.gif LogicalCallContext context2 = CallContext.GetLogicalCallContext(); InBlock.gif obj1 = context2.HostContext; ExpandedSubBlockEnd.gif } InBlock.gifreturn obj1; ExpandedSubBlockEnd.gif } ExpandedBlockEnd.gif}
显然,非 Web 应用 HttpContext.Current 返回 null 是因为 
ContextBase.Current as HttpContext 这么一句,返回的 null 。

ContextBase.Current 是有值的,但是由于非 Web 应用,返回的 Object 无法转换为HttpContext,而返回 null 的。
所以, HttpContext.Current.Cache 只可能用于 Web 应用的缓存。 而且是跟 HttpContext 紧密联系的。

三、HttpRuntime.Cache 可用于非 Web 应用的缓存。
比如我如下的一个控制台程序,是可以正常读写缓存的。而这里当然是不可以使用  HttpContext.Cache 的。
 
None.gif static void Main( string [] args) ExpandedBlockStart.gif { InBlock.gif System.Web.Caching.Cache c = System.Web.HttpRuntime.Cache; InBlock.gifif (c != null) ExpandedSubBlockStart.gif{ InBlock.gif c.Insert("1", "123141432432"); InBlock.gifInBlock.gifobject o = c.Get("1"); InBlock.gif Console.WriteLine(o); InBlock.gifExpandedSubBlockEnd.gif } InBlock.gif Console.ReadLine(); ExpandedBlockEnd.gif } None.gif
总结,
1、HttpRuntime.Cache 相当于就是一个缓存具体实现类,这个类虽然被放在了 System.Web 命名空间下了。但是非 Web 应用也是可以拿来用的。
2、HttpContext.Cache 是对上述缓存类的封装,由于封装到了 HttpContext ,局限于只能在知道 HttpContext 下使用,即只能用于 Web 应用。
综上所属,在可以的条件,尽量用  HttpRuntime.Cache ,而不是用  HttpContext.Cache 。


本文转自lidup 51CTO博客,原文链接:http://blog.51cto.com/lidup/218998,如需转载请自行联系原作者

相关文章
|
缓存
cache
cache
84 0
|
内存技术
|
存储 SQL 缓存
|
存储 缓存
cache control 里 no-cache 和 no-store 的区别
cache control 里 no-cache 和 no-store 的区别
1010 0
|
缓存 NoSQL Redis
|
PHP 缓存
|
Java API Memcache
|
缓存 数据库
|
缓存 JavaScript 前端开发