Showing posts with label Caching. Show all posts
Showing posts with label Caching. Show all posts

Wednesday, November 22, 2017

Useful caching pattern

One of the SO answers contains an interesting caching pattern, proposed by user Keith
static string GetCachedData(string key, DateTimeOffset offset)
{
    Lazy<string> lazyObject = new Lazy<string>(() => SomeHeavyAndExpensiveCalculationThatReturnsAString());

    var available = MemoryCache.Default.AddOrGetExisting(key, lazyObject, offset); 

    if (available == null)
       return lazyObject.Value;
    else
       return ((Lazy<string>)available).Value;
}
It relies on the MemoryCache::AddOrGetExisting returning null on the very first call that adds the item to the cache but returning the cached item in case it already exists in the cache. A clever trick worth of remembering.