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 { 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! /// private readonly Func _cacheFactory; /// /// Gets or creates a cache. /// public IAppPolicyCache GetOrCreate(TKey key) => _caches.GetOrAdd(key, k => _cacheFactory(k)); /// /// Tries to get a cache. /// protected 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. /// protected 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(); } } }