NotifyAwaiter.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // ReSharper disable ParameterHidesMember
  2. // ReSharper disable UnusedMember.Global
  3. using System;
  4. using System.Runtime.CompilerServices;
  5. namespace GodotTools.IdeMessaging.Utils
  6. {
  7. public class NotifyAwaiter<T> : INotifyCompletion
  8. {
  9. private Action? continuation;
  10. private Exception? exception;
  11. private T? result;
  12. public bool IsCompleted { get; private set; }
  13. public T GetResult()
  14. {
  15. if (exception != null)
  16. throw exception;
  17. return result!;
  18. }
  19. public void OnCompleted(Action continuation)
  20. {
  21. if (this.continuation != null)
  22. throw new InvalidOperationException("This awaiter already has a continuation.");
  23. this.continuation = continuation;
  24. }
  25. public void SetResult(T result)
  26. {
  27. if (IsCompleted)
  28. throw new InvalidOperationException("This awaiter is already completed.");
  29. IsCompleted = true;
  30. this.result = result;
  31. continuation?.Invoke();
  32. }
  33. public void SetException(Exception exception)
  34. {
  35. if (IsCompleted)
  36. throw new InvalidOperationException("This awaiter is already completed.");
  37. IsCompleted = true;
  38. this.exception = exception;
  39. continuation?.Invoke();
  40. }
  41. public NotifyAwaiter<T> Reset()
  42. {
  43. continuation = null;
  44. exception = null;
  45. result = default(T);
  46. IsCompleted = false;
  47. return this;
  48. }
  49. public NotifyAwaiter<T> GetAwaiter()
  50. {
  51. return this;
  52. }
  53. }
  54. }