前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >用HttpContext.Current.Cache还是HttpRuntime.Cache

用HttpContext.Current.Cache还是HttpRuntime.Cache

作者头像
崔文远TroyCui
发布2019-02-26 11:14:52
6910
发布2019-02-26 11:14:52
举报
文章被收录于专栏:远在上海远在上海

今天不说.NET Core里的新MemoryCache(Microsoft.Extensions.Caching.Memory),说说目前用得最广泛的.NET Framework下的缓存。

  1. HttpRuntime.Cache在非Web环境也支持,如WinForm、WPF
  2. HttpContext.Current.Cache只能用在Web中

MSDN上的解释如下: HttpContext.Current.Cache:为当前 HTTP 请求获取Cache对象。 HttpRuntime.Cache:获取当前应用程序的Cache对象。 为一探究竟,我们用.NET Reflector看看HttpContext.Cache和HttpRuntime.Cache的源码:

//System.Web.HttpContext.Cache属性实现 public sealed class HttpContext { public Cache Cache { get { return HttpRuntime.Cache; } } }

//System.Web.HttpRuntime.Cache属性实现 public sealed class HttpRuntime { public static Cache Cache { get { if (AspInstallDirectoryInternal == null) { throw new HttpException(SR.GetString(“Aspnet_not_installed”, new object[] { VersionInfo.SystemWebVersion })); } Cache cache = _theRuntime._cachePublic; if (cache == null) { CacheInternal cacheInternal = CacheInternal; CacheSection cacheSection = RuntimeConfig.GetAppConfig().Cache; cacheInternal.ReadCacheInternalConfig(cacheSection); _theRuntime._cachePublic = cacheInternal.CachePublic; cache = _theRuntime._cachePublic; } return cache; } } }

通过源码我们可以看出:HttpContext.Current.Cache是通过调用HttpRuntime.Cache实现的。

那么两者到底有没有区别的?既然两个指向的是同一Cache对象,两者的差别只能出现在HttpContext和HttpRuntime上了。

我们再来看看MSDN对HttpContext和HttpRuntime的定义: HttpContext:封装有关个别HTTP请求的所有HTTP特定的信息,HttpContext.Current为当前的HTTP请求获取HttpContext对象。 HttpRuntime:为当前应用程序提供一组ASP.NET运行时服务。

通过上面的定义可以看出:HttpRuntime.Cache相当于就是一个缓存具体实现类,这个类虽然被放在了System.Web命名空间下,但是非Web应用下也是可以使用。HttpContext.Current.Cache是对上述缓存类的封装,由于封装到了HttpContext类中,局限于只能在知道HttpContext下使用,即只能用于Web应用

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018年8月29日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档