using System.Collections.Concurrent;
using Umbraco.Extensions;
namespace Umbraco.Cms.Core.Cache;
///
/// Provides a base class for implementing a dictionary of .
///
/// The type of the dictionary key.
public abstract class AppPolicedCacheDictionary : IDisposable
where TKey : notnull
{
///
/// Gets the internal cache factory, for tests only!
///
private readonly Func _cacheFactory;
private readonly ConcurrentDictionary _caches = new();
private bool _disposedValue;
///
/// Initializes a new instance of the class.
///
///
protected AppPolicedCacheDictionary(Func cacheFactory) => _cacheFactory = cacheFactory;
public void Dispose() =>
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(true);
///
/// Gets or creates a cache.
///
public IAppPolicyCache GetOrCreate(TKey key)
=> _caches.GetOrAdd(key, k => _cacheFactory(k));
///
/// Removes a cache.
///
public void Remove(TKey key) => _caches.TryRemove(key, out _);
///
/// Removes all caches.
///
public void RemoveAll() => _caches.Clear();
///
/// Clears all caches.
///
public void ClearAllCaches()
{
foreach (IAppPolicyCache cache in _caches.Values)
{
cache.Clear();
}
}
///
/// Tries to get a cache.
///
protected Attempt Get(TKey key)
=> _caches.TryGetValue(key, out IAppPolicyCache? cache)
? Attempt.Succeed(cache)
: Attempt.Fail();
///
/// Clears a cache.
///
protected void ClearCache(TKey key)
{
if (_caches.TryGetValue(key, out IAppPolicyCache? cache))
{
cache.Clear();
}
}
protected virtual void Dispose(bool disposing)
{
if (!_disposedValue)
{
if (disposing)
{
foreach (IAppPolicyCache value in _caches.Values)
{
value.DisposeIfDisposable();
}
}
_disposedValue = true;
}
}
}