我一直在阅读一些有关 c# 3.5 中的缓存的内容。有点困惑,希望能澄清一下两者之间的区别
HttpContext.Current.Cache
对比 HttpRuntime.Cache
对比 System.Web.Caching.Cache
另外,我读过不推荐在非 Web 应用程序中使用上述任何一种,但它确实有效。有什么缺点?
最佳答案
System.Web.Caching.Cache
是为 Web 应用程序实现缓存的类型。 HttpContext.Current.Cache
只是一个包装器并返回 HttpRuntime.Cache
,它不过是 System.Web.Caching.Cache
的实例。
更新
引用Is it OK to use HttpRuntime.Cache outside ASP.NET applications?对于你的第二部分。
更新:为什么 HttpRuntime.Cache 需要包装?
在我个人看来,HttpContext
是传递给 IHttpHandler.ProcessPostBack
和 HttpApplication
公开的类型HttpContext
传递给 IHttpModule.Init
。这将确保使用方法注入(inject)来注入(inject)所有依赖项。因此,他们引入了一定程度的间接性。
处理程序和模块应该不知道托管它们的 HttpRuntime。当您在 ASP.NET 页面中时,建议使用 this.Page.Cache
而不是 HttpContext.Current.Cache
或 HttpRuntime.Cache
因为使用 HttpContext.Current 会涉及解析当前线程的开销,而 HttpRuntime.Cache
会创建外部依赖项。 Page.Cache
使用传递给 ProcessRequest
HttpContext.Cache
进行初始化
关于c# - HttpContext.Current.Cache 与 HttpRuntime.Cache,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10310187/