我知道有一个非常相似的问题 这里 但是我希望得到更好的解释。为什么我要使用httpcontext.cache而不是httpruntime.cache。

在文章中 使用ASP.NET模拟Windows服务以运行计划的作业 奥马尔使用httpcontext存储他的缓存项目,但是当杰夫·阿特伍德(Jeff Atwood)实施它时 这里 他选择使用httpruntime。显然,在这种特殊情况下,这是有道理的,因为您不必执行Web请求就将缓存项添加回HTTPContext中。

但是,我正在寻找一些何时使用一个与另一个使用的好指针。

有帮助吗?

解决方案

最后,它确实是相同的缓存 HttpContext.Current 有时可能是零的(当不在Web上下文中,或在Web上下文中,但尚未构建)。您可以始终使用 HttpRuntime.Cache.

其他提示

当您在常规网页中时,您可以安全地使用 HttpContext.Cache 或只是 Cache 页面的属性。

如果您正在执行不在页面中的事情,则通常需要使用 HttpRuntime.Cache 安全地访问它。

在某些情况下,您可以知道是否存在HTTP上下文,例如,如果您从网页启动单独的线程,则该线程没有HTTP上下文。在其他情况下,您有时可能会有HTTP上下文,例如 Application_Start 方法IN global.asax, ,因为有一个请求,因此可能并不总是启动应用程序。

I find it misleading too although we all know it just returns HttpRuntime.Cache internally. Also the HttpRuntime is kind of a bad choice to expose the Cache I guess.

Everyone sais how Session is session-level cache and the Cache we're talking about is application-level. I would prefer to have Application.Cache as the cache we're using today and HttpContext.Cache to refer to what's known as HttpContext.Items.

As for answering your question, I think we should all stick to the HttpRuntime.Cache making our code clearer even if we do have various ways to access it. And when you seriously plan to use it you'd better wrap your own API and have that internally call the HttpRuntime's or any other cache implementation (EntLib, Velocity, etc...).

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top