Caching in on .Net

Just a quick post about a new feature I wasn’t aware of. If you need to cache objects in .Net, before you run off and write a custom cache abstraction to divorce your code from System.Web or to scale out your cache, check out the abstract class System.Runtime.Caching.ObjectCache. It’s based on a mature cache model and is part of the .Net framework. I haven’t researched it, but there are probably implementations for you favorite distribute cache platforms already and if there isn’t one I bet its not too difficult to roll your own with ObjectCache as the base.

Also, if you need a simple in-memory cache without the System.Web headache, try System.Runtime.Caching.MemoryCache. MemoryCache.Default gives you an in-memory cache similar to the cache in ASP.NET, but for use in any .Net project without the System.Web dependency. It also provides ways to override and modify cache behavior.

So, you get a default cache with mature implementation of caching with the ability to add your own customizations, what more could you ask for. How about a thread safe dictionary? I stumbled upon MemoryCache as I was researching new ways to make a thread safe dictionary. Well I guess I will go back to learning about System.Collections.Concurrent.ConcurrentDictionary<TKey, TValue>. Wish me luck and if you have any advice, please let me know.