What's the difference between the HttpRuntime Cache and the HttpContext Cache?
Asked Answered
T

3

19

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.

Tatianna answered 10/7, 2009 at 11:17 Comment(0)
G
13

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.

Gomez answered 10/7, 2009 at 11:21 Comment(0)
C
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.

Candlewood answered 10/7, 2009 at 12:8 Comment(0)
M
2

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

Mozzarella answered 11/7, 2009 at 10:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.