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();
This is really bad advice. This will block 2 threads requesting 2 different keys. You should lock by the key value.
The code is inline. If you want to reuse it then it shuld be like you said lock on key