Locking pattern for proper use of .NET MemoryCache

前端 未结 9 2097
栀梦
栀梦 2020-11-30 17:13

I assume this code has concurrency issues:

const string CacheKey = \"CacheKey\";
static string GetCachedData()
{
    string expensiveString =null;
    if (Me         


        
9条回答
  •  再見小時候
    2020-11-30 17:57

    I've solved this issue by making use of the AddOrGetExisting method on the MemoryCache and the use of Lazy initialization.

    Essentially, my code looks something like this:

    static string GetCachedData(string key, DateTimeOffset offset)
    {
        Lazy lazyObject = new Lazy(() => SomeHeavyAndExpensiveCalculationThatReturnsAString());
        var returnedLazyObject = MemoryCache.Default.AddOrGetExisting(key, lazyObject, offset); 
        if (returnedLazyObject == null)
           return lazyObject.Value;
        return ((Lazy) returnedLazyObject).Value;
    }
    

    Worst case scenario here is that you create the same Lazy object twice. But that is pretty trivial. The use of AddOrGetExisting guarantees that you'll only ever get one instance of the Lazy object, and so you're also guaranteed to only call the expensive initialization method once.

提交回复
热议问题