You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

75 lines
1.8 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. namespace Apewer.Internals
  5. {
  6. /// <summary>锁。</summary>
  7. internal class Locker
  8. {
  9. Dictionary<int, Class<object>> _pool = new Dictionary<int, Class<object>>();
  10. /// <summary>标记指定的字符串。</summary>
  11. static int Key(string s) => s == null ? 0 : s.GetHashCode();
  12. /// <summary>清除所有缓存的锁。</summary>
  13. public void Clear()
  14. {
  15. lock (_pool)
  16. {
  17. _pool.Clear();
  18. }
  19. }
  20. /// <summary>锁定字符串,执行 Action。</summary>
  21. public void InLock(string text, Action action)
  22. {
  23. if (action == null) return;
  24. var key = Key(text);
  25. Class<object> locker;
  26. lock (_pool)
  27. {
  28. if (!_pool.TryGetValue(key, out locker))
  29. {
  30. locker = new Class<object>();
  31. _pool.Add(key, locker);
  32. }
  33. }
  34. lock (locker.Value)
  35. {
  36. action.Invoke();
  37. }
  38. }
  39. /// <summary>锁定字符串,执行 Func。</summary>
  40. public T InLock<T>(string text, Func<T> func)
  41. {
  42. if (func == null) return default;
  43. var key = Key(text);
  44. Class<object> locker;
  45. lock (_pool)
  46. {
  47. if (!_pool.TryGetValue(key, out locker))
  48. {
  49. locker = new Class<object>();
  50. _pool.Add(key, locker);
  51. }
  52. }
  53. T result;
  54. lock (locker.Value)
  55. {
  56. result = func.Invoke();
  57. }
  58. return result;
  59. }
  60. }
  61. }