NetThreadComponentSystem.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. using System;
  2. using System.Threading;
  3. namespace ET
  4. {
  5. [ObjectSystem]
  6. public class NetThreadComponentAwakeSystem: AwakeSystem<NetThreadComponent>
  7. {
  8. public override void Awake(NetThreadComponent self)
  9. {
  10. NetThreadComponent.Instance = self;
  11. #if NET_THREAD
  12. self.Thread = new Thread(self.Loop);
  13. self.ThreadSynchronizationContext = new ThreadSynchronizationContext(self.Thread.ManagedThreadId);
  14. self.Thread.Start();
  15. #else
  16. self.ThreadSynchronizationContext = ThreadSynchronizationContext.Instance;
  17. #endif
  18. }
  19. }
  20. #if !NET_THREAD
  21. [ObjectSystem]
  22. public class NetThreadComponentUpdateSystem: LateUpdateSystem<NetThreadComponent>
  23. {
  24. public override void LateUpdate(NetThreadComponent self)
  25. {
  26. foreach (AService service in self.Services)
  27. {
  28. service.Update();
  29. }
  30. }
  31. }
  32. #endif
  33. [ObjectSystem]
  34. public class NetThreadComponentDestroySystem: DestroySystem<NetThreadComponent>
  35. {
  36. public override void Destroy(NetThreadComponent self)
  37. {
  38. self.Stop();
  39. }
  40. }
  41. public static class NetThreadComponentSystem
  42. {
  43. #region 主线程
  44. public static void Stop(this NetThreadComponent self)
  45. {
  46. #if NET_THREAD
  47. self.ThreadSynchronizationContext.Post(()=>{self.isRun = false;});
  48. #endif
  49. }
  50. public static void Add(this NetThreadComponent self, AService kService)
  51. {
  52. // 这里要去下一帧添加,避免foreach错误
  53. self.ThreadSynchronizationContext.PostNext(() =>
  54. {
  55. if (kService.IsDispose())
  56. {
  57. return;
  58. }
  59. self.Services.Add(kService);
  60. });
  61. }
  62. public static void Remove(this NetThreadComponent self, AService kService)
  63. {
  64. // 这里要去下一帧删除,避免foreach错误
  65. self.ThreadSynchronizationContext.PostNext(() =>
  66. {
  67. if (kService.IsDispose())
  68. {
  69. return;
  70. }
  71. self.Services.Remove(kService);
  72. });
  73. }
  74. #endregion
  75. #if NET_THREAD
  76. #region 网络线程
  77. public static void Loop(this NetThreadComponent self)
  78. {
  79. self.isRun = true;
  80. while (true)
  81. {
  82. try
  83. {
  84. if (!self.isRun)
  85. {
  86. return;
  87. }
  88. self.ThreadSynchronizationContext.Update();
  89. foreach (AService service in self.Services)
  90. {
  91. service.Update();
  92. }
  93. }
  94. catch (Exception e)
  95. {
  96. Log.Error(e);
  97. }
  98. Thread.Sleep(1);
  99. }
  100. }
  101. #endregion
  102. #endif
  103. }
  104. }