MemoryCache Thread Safety, Is Locking Necessary?

前端 未结 7 573
你的背包
你的背包 2020-12-07 18:34

For starters let me just throw it out there that I know the code below is not thread safe (correction: might be). What I am struggling with is finding an implementation that

相关标签:
7条回答
  • 2020-12-07 19:02

    The cache is threadsafe, but like others have stated, its possible that GetOrAdd will call the func multiple types if call from multiple types.

    Here is my minimal fix on that

    private readonly SemaphoreSlim _cacheLock = new SemaphoreSlim(1);
    

    and

    await _cacheLock.WaitAsync();
    var data = await _cache.GetOrCreateAsync(key, entry => ...);
    _cacheLock.Release();
    
    0 讨论(0)
提交回复
热议问题