views:

1195

answers:

3

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.

+2  A: 

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.

Doron Yaacoby
A: 

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.

Guffa
+1  A: 

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