ActorProxyComponent.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. using System.Collections.Generic;
  2. namespace ETModel
  3. {
  4. [ObjectSystem]
  5. public class ActorProxyComponentSystem : StartSystem<ActorProxyComponent>
  6. {
  7. // 每10s扫描一次过期的actorproxy进行回收,过期时间是1分钟
  8. public override async void Start(ActorProxyComponent self)
  9. {
  10. List<long> timeoutActorProxyIds = new List<long>();
  11. while (true)
  12. {
  13. await Game.Scene.GetComponent<TimerComponent>().WaitAsync(10000);
  14. if (self.IsDisposed)
  15. {
  16. return;
  17. }
  18. timeoutActorProxyIds.Clear();
  19. long timeNow = TimeHelper.Now();
  20. foreach (long id in self.ActorProxys.Keys)
  21. {
  22. ActorProxy actorProxy = self.Get(id);
  23. if (actorProxy == null)
  24. {
  25. continue;
  26. }
  27. if (timeNow < actorProxy.LastSendTime + 60 * 1000)
  28. {
  29. continue;
  30. }
  31. timeoutActorProxyIds.Add(id);
  32. }
  33. foreach (long id in timeoutActorProxyIds)
  34. {
  35. self.Remove(id);
  36. }
  37. }
  38. }
  39. }
  40. public class ActorProxyComponent: Component
  41. {
  42. public readonly Dictionary<long, ActorProxy> ActorProxys = new Dictionary<long, ActorProxy>();
  43. public override void Dispose()
  44. {
  45. if (this.IsDisposed)
  46. {
  47. return;
  48. }
  49. base.Dispose();
  50. foreach (ActorProxy actorProxy in this.ActorProxys.Values)
  51. {
  52. actorProxy.Dispose();
  53. }
  54. this.ActorProxys.Clear();
  55. }
  56. public ActorProxy Get(long id)
  57. {
  58. if (this.ActorProxys.TryGetValue(id, out ActorProxy actorProxy))
  59. {
  60. return actorProxy;
  61. }
  62. actorProxy = ComponentFactory.CreateWithId<ActorProxy>(id);
  63. this.ActorProxys[id] = actorProxy;
  64. return actorProxy;
  65. }
  66. public ActorProxy GetWithActorId(long actorId)
  67. {
  68. if (this.ActorProxys.TryGetValue(actorId, out ActorProxy actorProxy))
  69. {
  70. return actorProxy;
  71. }
  72. actorProxy = ComponentFactory.CreateWithId<ActorProxy>(actorId);
  73. actorProxy.ActorId = actorId;
  74. actorProxy.MaxFailTimes = 0;
  75. this.ActorProxys[actorId] = actorProxy;
  76. return actorProxy;
  77. }
  78. public void Remove(long id)
  79. {
  80. ActorProxy actorProxy;
  81. if (!this.ActorProxys.TryGetValue(id, out actorProxy))
  82. {
  83. return;
  84. }
  85. this.ActorProxys.Remove(id);
  86. actorProxy.Dispose();
  87. }
  88. }
  89. }