How should I populate MemoryCache without creating an instance of an object that will be cached separately?

The MemoryCache class provides a method called . AddOrGetExisting which is a thread-safe way to get, if it exists, and adds if it does not exist.

This method returns NULLif the cached object does not already exist. I think I understand the value of this because it provides user feedback regarding its existence in the cache.

My cache resolver is as follows:

private static T GetCachedCollection<T>(Guid cacheKey, Lazy<T> initializer)
{
    return (T) (MemoryCache.Default.AddOrGetExisting(cacheKey.ToString(), initializer.Value, _policy) ?? initializer.Value);
}

What I'm trying to accomplish is that the object is not created if it is not needed, and if necessary, I do not want to build it twice.

I have a problem: when I pass .Valuemy type Lazyas a parameter, it can call the initializer regardless of whether the item is found in the cache or not. However, if I understand JIT correctly, it will pass the delegate to the method and does not call it.

How should I achieve these goals:

  • Do not call an object initializer if it already exists in the cache
  • If it is not in the cache, then it is called only once.
+4
source share
1 answer

Do not store the object in cache, save Lazy.

private static T GetCachedCollection<T>(Guid cacheKey, Lazy<T> initializer)
{
    var cachedValue = (Lazy<T>)(MemoryCache.Default.AddOrGetExisting(
        cacheKey.ToString(), initializer, _policy) ?? initializer);
    return cachedValue.Value;
}
+7
source

All Articles