AsyncOperationBase.cs 1.9 KB

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