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 lazyObject = new Lazy(() => SomeHeavyAndExpensiveCalculationThatReturnsAString());

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

    if (available == null)
       return lazyObject.Value;
    else
       return ((Lazy)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.

No comments: