Locking pattern for proper use of .NET MemoryCache

前端 未结 9 2096
栀梦
栀梦 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:33

    There is an open source library [disclaimer: that I wrote]: LazyCache that IMO covers your requirement with two lines of code:

    IAppCache cache = new CachingService();
    var cachedResults = cache.GetOrAdd("CacheKey", 
      () => SomeHeavyAndExpensiveCalculation());
    

    It has built in locking by default so the cacheable method will only execute once per cache miss, and it uses a lambda so you can do "get or add" in one go. It defaults to 20 minutes sliding expiration.

    There's even a NuGet package ;)

提交回复
热议问题