AsyncOperationBase.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Threading.Tasks;
  5. namespace GFGGame
  6. {
  7. public abstract class AsyncOperationBase : IEnumerator
  8. {
  9. // 用户请求的回调
  10. private Action<AsyncOperationBase> _callback;
  11. /// <summary>
  12. /// 状态
  13. /// </summary>
  14. public EOperationStatus Status { get; protected set; } = EOperationStatus.None;
  15. /// <summary>
  16. /// 错误信息
  17. /// </summary>
  18. public string Error { get; protected set; }
  19. /// <summary>
  20. /// 处理进度
  21. /// </summary>
  22. public float Progress { get; protected set; }
  23. /// <summary>
  24. /// 是否已经完成
  25. /// </summary>
  26. public bool IsDone
  27. {
  28. get
  29. {
  30. return Status == EOperationStatus.Failed || Status == EOperationStatus.Succeed;
  31. }
  32. }
  33. /// <summary>
  34. /// 完成事件
  35. /// </summary>
  36. public event Action<AsyncOperationBase> Completed
  37. {
  38. add
  39. {
  40. if (IsDone)
  41. value.Invoke(this);
  42. else
  43. _callback += value;
  44. }
  45. remove
  46. {
  47. _callback -= value;
  48. }
  49. }
  50. /// <summary>
  51. /// 异步操作任务
  52. /// </summary>
  53. public Task Task
  54. {
  55. get
  56. {
  57. if (_taskCompletionSource == null)
  58. {
  59. _taskCompletionSource = new TaskCompletionSource<object>();
  60. if (IsDone)
  61. _taskCompletionSource.SetResult(null);
  62. }
  63. return _taskCompletionSource.Task;
  64. }
  65. }
  66. internal abstract void Start();
  67. internal abstract void Update();
  68. internal void Finish()
  69. {
  70. Progress = 1f;
  71. _callback?.Invoke(this);
  72. if (_taskCompletionSource != null)
  73. _taskCompletionSource.TrySetResult(null);
  74. }
  75. /// <summary>
  76. /// 清空完成回调
  77. /// </summary>
  78. protected void ClearCompletedCallback()
  79. {
  80. _callback = null;
  81. }
  82. #region 异步编程相关
  83. bool IEnumerator.MoveNext()
  84. {
  85. return !IsDone;
  86. }
  87. void IEnumerator.Reset()
  88. {
  89. }
  90. object IEnumerator.Current => null;
  91. private TaskCompletionSource<object> _taskCompletionSource;
  92. #endregion
  93. }
  94. }