ActorProxyComponent.cs 1.7 KB

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