Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 220
Micah Avatar asked Jul 10 '09 11:07

Micah


People also ask

What is HttpContext cache?

HttpContext. Current. Cache is a class that provides caching of any kind of serializable objects. It in itself equates to HttpRuntime. Cache to muddy your waters even more.

Is HttpContext current Cache thread safe?

The HttpContext is NOT thread safe, accessing it from multiple threads can result in exceptions, data corruption and generally unpredictable results.

Where is HttpRuntime cache stored?

Cache is stored in web server memory.

Is HttpRuntime Cache thread safe?

Cache object itself is thread safe meaning that storing and reading from it are thread safe but obviously objects that you store inside might not be thread safe.


1 Answers

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.

like image 189
Doron Yaacoby Avatar answered Oct 04 '22 20:10

Doron Yaacoby