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.
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.
The HttpContext is NOT thread safe, accessing it from multiple threads can result in exceptions, data corruption and generally unpredictable results.
Cache is stored in web server memory.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With