using System.Collections.Concurrent; using System.Diagnostics.CodeAnalysis; namespace PCL.Core.App.Configuration; public struct ConfigValueCache() { private TValue? _cachedValue; private bool _hasCachedValue = false; private readonly ConcurrentDictionary _cacheWithContext = []; /// /// 检查指定上下文参数的缓存是否存在。 /// /// 上下文参数 public bool Exists(object? argument = null) { return (argument is null) ? _hasCachedValue : _cacheWithContext.ContainsKey(argument); } /// /// 尝试读取缓存值。 /// /// 若已缓存则为输出值,否则为默认值 /// 上下文参数 /// 若已缓存则为 true,否则为 false public bool TryRead( [NotNullWhen(true)] out TValue? value, object? argument = null) { bool result; if (argument is not null) result = _cacheWithContext.TryGetValue(argument, out value); else { if (_hasCachedValue) { value = _cachedValue!; result = true; } else { value = default; result = false; } } return result; } /// /// 写入缓存值。 /// /// 输入值 /// 上下文参数 public void Write(TValue value, object? argument = null) { if (argument is not null) { _cacheWithContext[argument] = value; return; } _hasCachedValue = true; _cachedValue = value; } /// /// 清除缓存值。
/// 若缓存存在则清除并返回 true,否则返回 false。 ///
/// 上下文参数 public bool Invalidate(object? argument) { if (argument is not null) return _cacheWithContext.TryRemove(argument, out _); if (!_hasCachedValue) return false; _cachedValue = default; _hasCachedValue = false; return true; } public void InvalidateAll() { _cacheWithContext.Clear(); _cachedValue = default; _hasCachedValue = false; } }