MemoryCache, caching in .NET 4

Having used the Enterprise Application Blocks in the past I’ve been well aware of the capabilities of the caching block, but recently was looking for some caching for a small application I have and stumbled across the MemoryCache which looks like it’s the replacement for the Caching Block.

It supports caching policy’s such as absolute expiration and sliding expiration.

You can create multiple instances of a MemoryCache or use a singleton in the form of MemoryCache.Default in the typical scenarios where only a single instance of the cache is required.

A simple example is shown below

MemoryCache cache = MemoryCache.Default;

cache.Add("Key", "Value", new DateTimeOffset(DateTime.Now.AddSeconds(10));
object o = cache.Get("Key");

In the above (fairly useless) example we get the default instance of the cache and then add a key and value to the cache with an absolutely expiry in 10 seconds time. We then get the item from the cache and ten seconds later it will have been removed from the cache.

When I get around to it I’ll amend with some better examples.