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