LazyPromise.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. using System;
  2. using System.Threading;
  3. namespace ETModel
  4. {
  5. internal sealed class LazyPromise: IAwaiter
  6. {
  7. private Func<ETTask> factory;
  8. private ETTask value;
  9. public LazyPromise(Func<ETTask> factory)
  10. {
  11. this.factory = factory;
  12. }
  13. private void Create()
  14. {
  15. var f = Interlocked.Exchange(ref factory, null);
  16. if (f != null)
  17. {
  18. value = f();
  19. }
  20. }
  21. public bool IsCompleted
  22. {
  23. get
  24. {
  25. Create();
  26. return value.IsCompleted;
  27. }
  28. }
  29. public AwaiterStatus Status
  30. {
  31. get
  32. {
  33. Create();
  34. return value.Status;
  35. }
  36. }
  37. public void GetResult()
  38. {
  39. Create();
  40. value.GetResult();
  41. }
  42. void IAwaiter.GetResult()
  43. {
  44. GetResult();
  45. }
  46. public void UnsafeOnCompleted(Action continuation)
  47. {
  48. Create();
  49. value.GetAwaiter().UnsafeOnCompleted(continuation);
  50. }
  51. public void OnCompleted(Action continuation)
  52. {
  53. UnsafeOnCompleted(continuation);
  54. }
  55. }
  56. internal sealed class LazyPromise<T>: IAwaiter<T>
  57. {
  58. private Func<ETTask<T>> factory;
  59. private ETTask<T> value;
  60. public LazyPromise(Func<ETTask<T>> factory)
  61. {
  62. this.factory = factory;
  63. }
  64. private void Create()
  65. {
  66. var f = Interlocked.Exchange(ref factory, null);
  67. if (f != null)
  68. {
  69. value = f();
  70. }
  71. }
  72. public bool IsCompleted
  73. {
  74. get
  75. {
  76. Create();
  77. return value.IsCompleted;
  78. }
  79. }
  80. public AwaiterStatus Status
  81. {
  82. get
  83. {
  84. Create();
  85. return value.Status;
  86. }
  87. }
  88. public T GetResult()
  89. {
  90. Create();
  91. return value.Result;
  92. }
  93. void IAwaiter.GetResult()
  94. {
  95. GetResult();
  96. }
  97. public void UnsafeOnCompleted(Action continuation)
  98. {
  99. Create();
  100. value.GetAwaiter().UnsafeOnCompleted(continuation);
  101. }
  102. public void OnCompleted(Action continuation)
  103. {
  104. UnsafeOnCompleted(continuation);
  105. }
  106. }
  107. }