C# - Great and simple implementation of MemoryCache

This week I had to implement some caching in an application. I decided to use the MemoryCache as that was built into C# and I had also used this years before.

However I did not want to start from scratch. I wanted a very simple implementation. Basicly just caching something or retrieving it. I looked around the internet and came upon the example made on blog.falafel.com. It was the most simple and easy way to use the MemoryCache I could find. It uses a Lazy and the AddOrGetExisting method of MemoryCache. The Lazy makes sure that whatever you are caching is only called once (which is the time consuming part of your code) and only when/if needed. The GetOrAddExisting is a nice way to - yes, get or add the object. instead of caring about updating and removing from cache you get the object if it's there or it is added.

The solution does not set up a specific CacheItemPolicy. It merely uses the default values. This is up to you to configure - you can get some pointers on how to do that here.

Since Falafel.com seems to be down (17 sept 2018) I will include the code here:

public static class ExampleCache 
    private static MemoryCache _cache = new MemoryCache("ExampleCache");
        
    public static object GetItem(string key) {
        return AddOrGetExisting(key, () => InitItem(key));
    }
    
    private static T AddOrGetExisting<T>(string key, Func<T> valueFactory)
    {
        var newValue = new Lazy<T>(valueFactory);
        var oldValue = _cache.AddOrGetExisting(key, newValue, new CacheItemPolicy()) as Lazy<T>;
        try
        {
            return (oldValue ?? newValue).Value;
        }
        catch
        {
            _cache.Remove(key);
            throw;
        }       
    }
    
    private static object InitItem(string key) {
        // Do something expensive to initialize item
        return new { Value = key.ToUpper() };
    }
}

Head over to blog.falafel.com and read the full article with examples there - "working with system.runtime.caching.memorycache"!