This commit is contained in:
Bjarke Berg
2024-03-15 15:34:00 +01:00
24 changed files with 224 additions and 54 deletions

View File

@@ -16,6 +16,9 @@ public class ObjectCacheAppCache : IAppPolicyCache, IDisposable
private readonly IOptions<MemoryCacheOptions> _options;
private readonly IHostEnvironment? _hostEnvironment;
private readonly ISet<string> _keys = new HashSet<string>();
private static readonly TimeSpan _readLockTimeout = TimeSpan.FromSeconds(5);
private static readonly TimeSpan _writeLockTimeout = TimeSpan.FromSeconds(5);
private readonly ReaderWriterLockSlim _locker = new(LockRecursionPolicy.SupportsRecursion);
private bool _disposedValue;
@@ -54,8 +57,10 @@ public class ObjectCacheAppCache : IAppPolicyCache, IDisposable
Lazy<object?>? result;
try
{
_locker.EnterReadLock();
if (_locker.TryEnterReadLock(_readLockTimeout) is false)
{
throw new TimeoutException("Timeout exceeded to the memory cache when getting item");
}
result = MemoryCache.Get(key) as Lazy<object?>; // null if key not found
}
finally
@@ -201,7 +206,10 @@ public class ObjectCacheAppCache : IAppPolicyCache, IDisposable
{
try
{
_locker.EnterWriteLock();
if (_locker.TryEnterWriteLock(_writeLockTimeout) is false)
{
throw new TimeoutException("Timeout exceeded to the memory cache when clearing item");
}
MemoryCache.Remove(key);
_keys.Remove(key);
@@ -286,7 +294,10 @@ public class ObjectCacheAppCache : IAppPolicyCache, IDisposable
{
try
{
_locker.EnterWriteLock();
if (_locker.TryEnterWriteLock(_writeLockTimeout) is false)
{
throw new TimeoutException("Timeout exceeded to the memory cache.");
}
// ToArray required to remove
foreach (var key in _keys.Where(predicate).ToArray())