MasterComponent.cs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System.Collections.Generic;
  2. using System.Threading.Tasks;
  3. using Base;
  4. namespace Model
  5. {
  6. public class LockInfo
  7. {
  8. public string Address;
  9. public TaskCompletionSource<bool> Tcs;
  10. public LockInfo(string address, TaskCompletionSource<bool> tcs)
  11. {
  12. this.Address = address;
  13. this.Tcs = tcs;
  14. }
  15. }
  16. [EntityEvent(typeof(MasterComponent))]
  17. public class MasterComponent : Component
  18. {
  19. /// 镜像的地址
  20. private readonly List<string> ghostsAddress = new List<string>();
  21. /// 当前获取锁的进程地址
  22. private string lockedAddress = "";
  23. /// 请求锁的队列
  24. private readonly Queue<LockInfo> queue = new Queue<LockInfo>();
  25. public void AddGhost(string address)
  26. {
  27. this.ghostsAddress.Add(address);
  28. }
  29. public void RemoveGhost(string address)
  30. {
  31. this.ghostsAddress.Remove(address);
  32. }
  33. public Task<bool> Lock(string address)
  34. {
  35. TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
  36. if (this.lockedAddress == "")
  37. {
  38. this.lockedAddress = address;
  39. tcs.SetResult(true);
  40. }
  41. else
  42. {
  43. LockInfo lockInfo = new LockInfo(address, tcs);
  44. this.queue.Enqueue(lockInfo);
  45. }
  46. return tcs.Task;
  47. }
  48. public void Release(string address)
  49. {
  50. if (this.lockedAddress != address)
  51. {
  52. Log.Error($"解锁地址与锁地址不匹配! {this.lockedAddress} {address}");
  53. return;
  54. }
  55. if (this.queue.Count == 0)
  56. {
  57. this.lockedAddress = "";
  58. return;
  59. }
  60. LockInfo lockInfo = this.queue.Dequeue();
  61. this.lockedAddress = lockInfo.Address;
  62. lockInfo.Tcs.SetResult(true);
  63. }
  64. }
  65. }