ETCancellationToken.cs 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using System;
  2. using System.Collections.Generic;
  3. namespace ET
  4. {
  5. public class ETCancellationToken
  6. {
  7. private HashSet<Action> actions = new HashSet<Action>();
  8. public void Add(Action callback)
  9. {
  10. // 如果action是null,绝对不能添加,要抛异常,说明有协程泄漏
  11. this.actions.Add(callback);
  12. }
  13. public void Remove(Action callback)
  14. {
  15. this.actions?.Remove(callback);
  16. }
  17. public bool IsDispose()
  18. {
  19. return this.actions == null;
  20. }
  21. public void Cancel()
  22. {
  23. if (this.actions == null)
  24. {
  25. return;
  26. }
  27. this.Invoke();
  28. }
  29. private void Invoke()
  30. {
  31. HashSet<Action> runActions = this.actions;
  32. this.actions = null;
  33. try
  34. {
  35. foreach (Action action in runActions)
  36. {
  37. action.Invoke();
  38. }
  39. }
  40. catch (Exception e)
  41. {
  42. ETTask.ExceptionHandler.Invoke(e);
  43. }
  44. }
  45. }
  46. }