AsyncScheduler.cs 8.6 KB

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