using System; using System.Collections.Generic; using static System.Collections.Specialized.BitVector32; namespace Apewer.Internals { /// 整数锁。 internal sealed class Int32Locker : Locker { /// 获取整数的哈希值。 protected override int GetHash(int target) => target; } /// 文本锁。 internal sealed class TextLocker : Locker { /// 获取文本的哈希值。 protected override int GetHash(string target) => target == null ? 0 : target.GetHashCode(); } /// 锁。 internal abstract class Locker { Dictionary> _pool = new Dictionary>(); /// 获取目标的哈希值。 protected abstract int GetHash(TTarget key); /// 清除所有缓存的锁。 public void Clear() { lock (_pool) { _pool.Clear(); } } Class GetLocker(TTarget target) { var key = GetHash(target); lock (_pool) { if (_pool.TryGetValue(key, out var locker)) { return locker; } else { locker = new Class(new object()); _pool.Add(key, locker); return locker; } } } /// 锁定目标,执行 Action。 public void InLock(TTarget target, Action action) { if (action == null) return; var locker = GetLocker(target); lock (locker.Value) action.Invoke(); } /// 锁定目标,执行 Func。 public TResult InLock(TTarget target, Func func) { if (func == null) return default; var locker = GetLocker(target); lock (locker.Value) return func.Invoke(); } } }