您的位置:首页 > 理论基础 > 计算机网络

HttpContext.Current.Cache vs. HttpRuntime.Cache

2008-07-15 23:47 441 查看
.NET中Cache有两种调用方式:HttpContext.Current.Cache 和 HttpRuntime.Cache,这两种方式有什么区别呢?我们先看MSDN上的解释:

HttpContext.Current.Cache:为当前 HTTP 请求获取Cache对象。

HttpRuntime.Cache:获取当前应用程序的Cache。

我们再用.NET Reflector工具看看HttpContext.Cache和HttpRuntime.Cache的实现:

//System.Web.HttpContext.Cache属性实现

public sealed class HttpContext

//System.Web.HttpRuntime.Cache属性实现

public sealed class HttpRuntime

class CacheTest

{

static void Main(string[] args)

{

System.Web.Caching.Cache httpRuntimeCache = System.Web.HttpRuntime.Cache;

httpRuntimeCache.Insert("httpRuntimeCache", "I am stored in HttpRuntime.Cache");

if (httpRuntimeCache != null)

{

Console.WriteLine("httpRuntimeCache:" + httpRuntimeCache["httpRuntimeCache"]);

}

System.Web.HttpContext httpContext = System.Web.HttpContext.Current;

if (httpContext == null)

{

Console.WriteLine("HttpContext object is null in Console Project");

}

else

{

System.Web.Caching.Cache httpContextCache = httpContext.Cache;

httpContextCache.Insert("httpContextCache", "I am stored in HttpRuntime.Cache");

if (httpContextCache == null)

{

Console.WriteLine("httpContextCache is null");

}

}

Console.ReadLine();

}

}

输出结果:httpRuntimeCache:I am stored in HttpRuntime.Cache

HttpContext object is null in Console Project

综上:我们在使用Cache时,尽量使用HttpRuntime.Cache,既能减少出错,也减少了一次函数调用。

参考资料:HttpRuntime.Cache 与HttpContext.Current.Cache的疑问,HttpRuntime.Cache vs. HttpContext.Current.Cache
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: