I need to use IDistributedCache
in my app and it could be MemoryDistributedCache
or RedisCache
as an underlying implementation. My understanding those are not thread-safe, so I created my own wrapper with usage of ReaderWriterLockSlim
.
ReaderWriterLockSlim
allows multiple threads for reading or exclusive access for writing. And now I wonder if it's the right tool for the job and if MemoryDistributedCache
and RedisCache
reading methods are thread-safe.
As to overall solution - I understand it takes time to store and read values from a distributed cache like Redis. But I don't have much choice as the values I store are even slower to get and manage.
Here's the snippet:
...
public async Task<byte[]> GetAsync(string key, CancellationToken token = new CancellationToken())
{
_cacheLock.EnterReadLock();
try
{
return await _cache.GetAsync(GetCacheKey(key), token);
}
finally
{
_cacheLock.ExitReadLock();
}
}
public async Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options, CancellationToken token = new CancellationToken())
{
_cacheLock.EnterWriteLock();
try
{
await _cache.SetAsync(GetCacheKey(key), value, options, token);
}
finally
{
_cacheLock.ExitWriteLock();
}
}
public async Task RemoveAsync(string key, CancellationToken token = new CancellationToken())
{
_cacheLock.EnterWriteLock();
try
{
await _cache.RemoveAsync(GetCacheKey(key), token);
}
finally
{
_cacheLock.ExitWriteLock();
}
}