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

六眼飞鱼酱① 提交于 2019-12-31 09:17:29

问题


I know there is a very similar question here but I was hoping to get a better explination. Why would I ever use HttpContext.Cache instead of HttpRuntime.Cache if the HttpContext really uses the HttpRuntime.Cache behind the scenes?

In the article Simulate a Windows Service using ASP.NET to run scheduled jobs Omar uses the HttpContext to store his cache items, but when Jeff Atwood Implemented it here he chose to use the HttpRuntime instead. Obviously in this particular situation it makes sense since since you don't have to do a web request to add the cache item back into the HttpContext.

However I'm looking for some good pointers as to when to use one versus the other.


回答1:


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.




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/1108990/whats-the-difference-between-the-httpruntime-cache-and-the-httpcontext-cache

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