diff --git a/Apewer/Internals/Locker.cs b/Apewer/Internals/Locker.cs index c38bdc5..d44f34b 100644 --- a/Apewer/Internals/Locker.cs +++ b/Apewer/Internals/Locker.cs @@ -1,18 +1,36 @@ using System; using System.Collections.Generic; -using System.Text; +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 class Locker + internal abstract class Locker { Dictionary> _pool = new Dictionary>(); - /// 标记指定的字符串。 - static int Key(string s) => s == null ? 0 : s.GetHashCode(); + /// 获取目标的哈希值。 + protected abstract int GetHash(TTarget key); /// 清除所有缓存的锁。 public void Clear() @@ -23,50 +41,40 @@ namespace Apewer.Internals } } - /// 锁定字符串,执行 Action。 - public void InLock(string text, Action action) + Class GetLocker(TTarget target) { - if (action == null) return; - - var key = Key(text); - Class locker; + var key = GetHash(target); lock (_pool) { - if (!_pool.TryGetValue(key, out locker)) + if (_pool.TryGetValue(key, out var locker)) { - locker = new Class(); + return locker; + } + else + { + locker = new Class(new object()); _pool.Add(key, locker); + return locker; } } + } - lock (locker.Value) - { - action.Invoke(); - } + /// 锁定目标,执行 Action。 + public void InLock(TTarget target, Action action) + { + if (action == null) return; + + var locker = GetLocker(target); + lock (locker.Value) action.Invoke(); } - /// 锁定字符串,执行 Func。 - public T InLock(string text, Func func) + /// 锁定目标,执行 Func。 + public TResult InLock(TTarget target, Func func) { if (func == null) return default; - var key = Key(text); - Class locker; - lock (_pool) - { - if (!_pool.TryGetValue(key, out locker)) - { - locker = new Class(); - _pool.Add(key, locker); - } - } - - T result; - lock (locker.Value) - { - result = func.Invoke(); - } - return result; + var locker = GetLocker(target); + lock (locker.Value) return func.Invoke(); } } diff --git a/Apewer/TextUtility.cs b/Apewer/TextUtility.cs index 0170d82..d065d05 100644 --- a/Apewer/TextUtility.cs +++ b/Apewer/TextUtility.cs @@ -1065,7 +1065,7 @@ namespace Apewer #region Lock - static Locker _locker = new Locker(); + static TextLocker _locker = new TextLocker(); /// 锁定文本,在锁中执行函数。 /// 要锁定的文本。