using System; using System.Collections.Generic; using System.Text; namespace Apewer.Internals { /// 锁。 internal class Locker { Dictionary> _pool = new Dictionary>(); /// 标记指定的字符串。 static int Key(string s) => s == null ? 0 : s.GetHashCode(); /// 清除所有缓存的锁。 public void Clear() { lock (_pool) { _pool.Clear(); } } /// 锁定字符串,执行 Action。 public void InLock(string text, Action action) { if (action == null) return; var key = Key(text); Class locker; lock (_pool) { if (!_pool.TryGetValue(key, out locker)) { locker = new Class(); _pool.Add(key, locker); } } lock (locker.Value) { action.Invoke(); } } /// 锁定字符串,执行 Func。 public T InLock(string text, 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; } } }