AsyncScheduler.cs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT License.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Runtime.ExceptionServices;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. namespace System.Reactive.Concurrency
  8. {
  9. public static class AsyncScheduler
  10. {
  11. public static IAwaitable RendezVous(this IAsyncScheduler scheduler, CancellationToken token = default)
  12. {
  13. if (scheduler == null)
  14. throw new ArgumentNullException(nameof(scheduler));
  15. token.ThrowIfCancellationRequested();
  16. return new RendezVousAwaitable(scheduler, token);
  17. }
  18. public static IAwaitable RendezVous(this Task task, IAsyncScheduler scheduler, CancellationToken token = default)
  19. {
  20. if (task == null)
  21. throw new ArgumentNullException(nameof(task));
  22. if (scheduler == null)
  23. throw new ArgumentNullException(nameof(scheduler));
  24. return new TaskAwaitable(task, continueOnCapturedContext: false, scheduler, token);
  25. }
  26. public static IAwaitable<T> RendezVous<T>(this Task<T> task, IAsyncScheduler scheduler, CancellationToken token = default)
  27. {
  28. if (task == null)
  29. throw new ArgumentNullException(nameof(task));
  30. if (scheduler == null)
  31. throw new ArgumentNullException(nameof(scheduler));
  32. return new TaskAwaitable<T>(task, continueOnCapturedContext: false, scheduler, token);
  33. }
  34. public static IAwaitable RendezVous(this ValueTask task, IAsyncScheduler scheduler, CancellationToken token = default)
  35. {
  36. if (scheduler == null)
  37. throw new ArgumentNullException(nameof(scheduler));
  38. return new ValueTaskAwaitable(task, continueOnCapturedContext: false, scheduler, token);
  39. }
  40. public static IAwaitable<T> RendezVous<T>(this ValueTask<T> task, IAsyncScheduler scheduler, CancellationToken token = default)
  41. {
  42. if (scheduler == null)
  43. throw new ArgumentNullException(nameof(scheduler));
  44. return new ValueTaskAwaitable<T>(task, continueOnCapturedContext: false, scheduler, token);
  45. }
  46. public static async ValueTask Delay(this IAsyncScheduler scheduler, TimeSpan dueTime, CancellationToken token = default)
  47. {
  48. if (scheduler == null)
  49. throw new ArgumentNullException(nameof(scheduler));
  50. var tcs = new TaskCompletionSource<bool>();
  51. var task = await scheduler.ScheduleAsync(ct =>
  52. {
  53. if (ct.IsCancellationRequested)
  54. {
  55. tcs.TrySetCanceled(ct);
  56. }
  57. else
  58. {
  59. tcs.SetResult(true);
  60. }
  61. return default;
  62. }, dueTime);
  63. using (token.Register(() => task.DisposeAsync()))
  64. {
  65. await tcs.Task;
  66. }
  67. }
  68. public static async ValueTask Delay(this IAsyncScheduler scheduler, DateTimeOffset dueTime, CancellationToken token = default)
  69. {
  70. if (scheduler == null)
  71. throw new ArgumentNullException(nameof(scheduler));
  72. var tcs = new TaskCompletionSource<bool>();
  73. var task = await scheduler.ScheduleAsync(ct =>
  74. {
  75. if (ct.IsCancellationRequested)
  76. {
  77. tcs.TrySetCanceled(ct);
  78. }
  79. else
  80. {
  81. tcs.SetResult(true);
  82. }
  83. return default;
  84. }, dueTime);
  85. using (token.Register(() => task.DisposeAsync()))
  86. {
  87. await tcs.Task;
  88. }
  89. }
  90. public static async ValueTask ExecuteAsync(this IAsyncScheduler scheduler, Func<CancellationToken, ValueTask> action, CancellationToken token = default)
  91. {
  92. var tcs = new TaskCompletionSource<object>();
  93. var d = await scheduler.ScheduleAsync(async ct =>
  94. {
  95. try
  96. {
  97. ct.ThrowIfCancellationRequested();
  98. await action(ct).RendezVous(scheduler, ct);
  99. }
  100. catch (OperationCanceledException ex) when (ex.CancellationToken == ct)
  101. {
  102. tcs.TrySetCanceled(ct);
  103. }
  104. catch (Exception ex)
  105. {
  106. tcs.TrySetException(ex);
  107. }
  108. finally
  109. {
  110. tcs.TrySetResult(null);
  111. }
  112. });
  113. using (token.Register(() =>
  114. {
  115. try
  116. {
  117. d.DisposeAsync();
  118. }
  119. finally
  120. {
  121. tcs.TrySetCanceled(token);
  122. }
  123. }))
  124. {
  125. await tcs.Task.ConfigureAwait(false);
  126. }
  127. }
  128. public static async ValueTask<TResult> ExecuteAsync<TResult>(this IAsyncScheduler scheduler, Func<CancellationToken, ValueTask<TResult>> action, CancellationToken token = default)
  129. {
  130. var tcs = new TaskCompletionSource<TResult>();
  131. var d = await scheduler.ScheduleAsync(async ct =>
  132. {
  133. var res = default(TResult);
  134. try
  135. {
  136. ct.ThrowIfCancellationRequested();
  137. res = await action(ct).RendezVous(scheduler, ct);
  138. }
  139. catch (OperationCanceledException ex) when (ex.CancellationToken == ct)
  140. {
  141. tcs.TrySetCanceled(ct);
  142. }
  143. catch (Exception ex)
  144. {
  145. tcs.TrySetException(ex);
  146. }
  147. finally
  148. {
  149. tcs.TrySetResult(res);
  150. }
  151. });
  152. using (token.Register(() =>
  153. {
  154. try
  155. {
  156. d.DisposeAsync();
  157. }
  158. finally
  159. {
  160. tcs.TrySetCanceled(token);
  161. }
  162. }))
  163. {
  164. return await tcs.Task.ConfigureAwait(false);
  165. }
  166. }
  167. private sealed class RendezVousAwaitable : IAwaitable, IAwaiter // PERF: Can we avoid these allocations?
  168. {
  169. private readonly IAsyncScheduler _scheduler;
  170. private readonly CancellationToken _token;
  171. private ExceptionDispatchInfo _error;
  172. public RendezVousAwaitable(IAsyncScheduler scheduler, CancellationToken token)
  173. {
  174. _scheduler = scheduler;
  175. _token = token;
  176. }
  177. public bool IsCompleted { get; private set; }
  178. public IAwaiter GetAwaiter() => this;
  179. public void GetResult()
  180. {
  181. if (!IsCompleted)
  182. {
  183. throw new InvalidOperationException(); // REVIEW: No support for blocking.
  184. }
  185. if (_error != null)
  186. {
  187. _error.Throw();
  188. }
  189. }
  190. public void OnCompleted(Action continuation)
  191. {
  192. var t = _scheduler.ExecuteAsync(ct =>
  193. {
  194. try
  195. {
  196. continuation();
  197. }
  198. catch (Exception ex)
  199. {
  200. _error = ExceptionDispatchInfo.Capture(ex);
  201. }
  202. finally
  203. {
  204. IsCompleted = true;
  205. }
  206. return default;
  207. }, _token);
  208. }
  209. }
  210. }
  211. }