Should I use HttpRuntime.Cache?
Asked Answered
R

1

42

I'm a beginner in asp.net, and have a few question of Cache:

  1. HttpRuntime.Cache only provides severals methods and I think I'm able to implement these methods with Dictionary by myself.
  2. If HttpRuntime.Cache is much better than Dictionary, why some people would like to implement their own cache framework.
  3. How about MS Enterprise Cache Block?
Roentgenogram answered 11/11, 2011 at 10:8 Comment(0)
N
99

HttpRuntime.Cache only provides severals methods and I think I'm able to implement these methods with Dictionary by myself.

You think wrong. HttpRuntime.Cache is much more than a simple dictionary. It offers thread-safety and cache expiration policies. It provides possibilities of using custom implementation and benefit from distributed caching which is helpful in web farms. Implementing this with dictionaries could be lots of work that you probably don't want to venture into as you will be basically reinventing the wheels and even if reinventing wheels doesn't bother you chances for getting it right are slim.

2)If HttpRuntime.Cache is much better than Dictionary, why some people would like to implement their own cache framework.

People wouldn't want to do that.

3) How about MS Enterprise Cache Block?

That's heavy artillery which is not always necessary when you need simple caching which could be achieved with what the framework already provides you out of the box.

Remark: In .NET 4.0 you should use the new System.Runtime.Caching namespace instead of HttpRuntime.Cache.

So to answer your question: Should I use HttpRuntime.Cache

Yes, unless you are using .NET 4.0 in which case you should use classes from the new System.Runtime.Caching namespace.

Nich answered 11/11, 2011 at 10:11 Comment(5)
Thanks for your wonderful answer. I have a further question: I have seen some people use HttpRuntime.Cache in a non-web application like Console, I think it's a little strange. Did you ever see that?Roentgenogram
@Domi.Zhang, yes, I have seen that. It works but requires a dependency on the System.Web assembly. That's the reason why Microsoft decided to externalize the caching into a separate assembly in .NET 4.0.Nich
Darin , What if I want the expiration times like in Httpruntime cache ? I couldnt find it in System.Runtime.CachingBroadcloth
@RoyiNamir, the .Add() method allows you to pass a CacheItemPolicy to control various options.Nich
Update on "console application usage" of HttpRuntime.Cache is a remarked warning in msdn documents here: "The Cache class is not intended for use outside of ASP.NET applications. It was designed and tested for use in ASP.NET to provide caching for Web applications. For other types of applications, such as console applications or Windows Forms applications, use the ObjectCache class."Cryptonymous

© 2022 - 2024 — McMap. All rights reserved.