What's the difference between the HttpRuntime Cache and the HttpContext Cache?

你离开我真会死。 提交于 2019-12-02 18:15:40
Doron Yaacoby

It really is the same cache at the end, only HttpContext.Current can sometimes be null (when not in a web context, or in a web context but not yet constructed). You'd be safe to always use HttpRuntime.Cache.

When you are in a regular web page, you can safely use HttpContext.Cache or just the Cache property of the page.

If you are doing something that's not in a page, you often need to use HttpRuntime.Cache to safely get access to it.

In some cases you can know if there is an http context or not, for example if you start a separate thread from a web page, that thread does not have http context. In other cases you may have an http context sometimes, like in the Application_Start method in global.asax, as the application may not always be started because there is a request.

user134706

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...).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!