OperationSystem.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. namespace GFGGame
  5. {
  6. internal class OperationSystem
  7. {
  8. private static readonly List<AsyncOperationBase> _operations = new List<AsyncOperationBase>(100);
  9. private static readonly List<AsyncOperationBase> _addList = new List<AsyncOperationBase>(100);
  10. private static readonly List<AsyncOperationBase> _removeList = new List<AsyncOperationBase>(100);
  11. // 计时器相关
  12. private static Stopwatch _watch;
  13. private static long _frameTime;
  14. /// <summary>
  15. /// 异步操作的最小时间片段
  16. /// </summary>
  17. public static long MaxTimeSlice { set; get; } = long.MaxValue;
  18. /// <summary>
  19. /// 处理器是否繁忙
  20. /// </summary>
  21. public static bool IsBusy
  22. {
  23. get
  24. {
  25. return _watch.ElapsedMilliseconds - _frameTime >= MaxTimeSlice;
  26. }
  27. }
  28. /// <summary>
  29. /// 初始化异步操作系统
  30. /// </summary>
  31. public static void Initialize()
  32. {
  33. _watch = Stopwatch.StartNew();
  34. }
  35. /// <summary>
  36. /// 更新异步操作系统
  37. /// </summary>
  38. public static void Update()
  39. {
  40. _frameTime = _watch.ElapsedMilliseconds;
  41. // 添加新的异步操作
  42. if (_addList.Count > 0)
  43. {
  44. for (int i = 0; i < _addList.Count; i++)
  45. {
  46. var operation = _addList[i];
  47. _operations.Add(operation);
  48. }
  49. _addList.Clear();
  50. }
  51. // 更新所有的异步操作
  52. foreach (var operation in _operations)
  53. {
  54. if (IsBusy)
  55. break;
  56. operation.Update();
  57. if (operation.IsDone)
  58. {
  59. _removeList.Add(operation);
  60. operation.Finish();
  61. }
  62. }
  63. // 移除已经完成的异步操作
  64. if (_removeList.Count > 0)
  65. {
  66. foreach (var operation in _removeList)
  67. {
  68. _operations.Remove(operation);
  69. }
  70. _removeList.Clear();
  71. }
  72. }
  73. /// <summary>
  74. /// 销毁异步操作系统
  75. /// </summary>
  76. public static void DestroyAll()
  77. {
  78. _operations.Clear();
  79. _addList.Clear();
  80. _removeList.Clear();
  81. _watch = null;
  82. _frameTime = 0;
  83. MaxTimeSlice = long.MaxValue;
  84. }
  85. /// <summary>
  86. /// 开始处理异步操作类
  87. /// </summary>
  88. public static void StartOperation(AsyncOperationBase operation)
  89. {
  90. _addList.Add(operation);
  91. operation.Start();
  92. }
  93. }
  94. }