ActorProxyComponent.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using System.Collections.Generic;
  2. namespace Model
  3. {
  4. [ObjectEvent]
  5. public class ActorProxyComponentEvent : ObjectEvent<ActorProxyComponent>, IStart
  6. {
  7. // 每分钟扫描一次过期的actorproxy进行回收,过期时间是5分钟
  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(60000);
  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 + 5 * 60000)
  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 ActorProxy Get(long id)
  45. {
  46. if (this.ActorProxys.TryGetValue(id, out ActorProxy actorProxy))
  47. {
  48. return actorProxy;
  49. }
  50. actorProxy = EntityFactory.CreateWithId<ActorProxy>(id);
  51. this.ActorProxys[id] = actorProxy;
  52. return actorProxy;
  53. }
  54. public void Remove(long id)
  55. {
  56. ActorProxy actorProxy;
  57. if (!this.ActorProxys.TryGetValue(id, out actorProxy))
  58. {
  59. return;
  60. }
  61. actorProxy.Dispose();
  62. }
  63. }
  64. }