Month: August 2019

A proper thread safe memory cache

The Core 2.2 IMemoryCache is in theory thread safe. But if you call GetOrCreateAsync from multiple threads the factory Func will be called multiple times. Which could be a bad thing. A very simple fix to this is using a semaphore.

Declare it and only let one concurrent request be granted.

private readonly SemaphoreSlim _cacheLock = new SemaphoreSlim(1);

Let one request the cache and when done release the semaphore.

await _cacheLock.WaitAsync();
var data = await _cache.GetOrCreateAsync(key, entry => ...);
_cacheLock.Release();