AsyncScheduler.cs 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the Apache 2.0 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 async Task Delay(this IAsyncScheduler scheduler, TimeSpan dueTime, CancellationToken token = default(CancellationToken))
  43. {
  44. if (scheduler == null)
  45. throw new ArgumentNullException(nameof(scheduler));
  46. var tcs = new TaskCompletionSource<bool>();
  47. var task = await scheduler.ScheduleAsync(ct =>
  48. {
  49. if (ct.IsCancellationRequested)
  50. {
  51. tcs.TrySetCanceled(ct);
  52. }
  53. else
  54. {
  55. tcs.SetResult(true);
  56. }
  57. return Task.CompletedTask;
  58. }, dueTime);
  59. using (token.Register(() => task.DisposeAsync()))
  60. {
  61. await tcs.Task;
  62. }
  63. }
  64. public static async Task Delay(this IAsyncScheduler scheduler, DateTimeOffset dueTime, CancellationToken token = default(CancellationToken))
  65. {
  66. if (scheduler == null)
  67. throw new ArgumentNullException(nameof(scheduler));
  68. var tcs = new TaskCompletionSource<bool>();
  69. var task = await scheduler.ScheduleAsync(ct =>
  70. {
  71. if (ct.IsCancellationRequested)
  72. {
  73. tcs.TrySetCanceled(ct);
  74. }
  75. else
  76. {
  77. tcs.SetResult(true);
  78. }
  79. return Task.CompletedTask;
  80. }, dueTime);
  81. using (token.Register(() => task.DisposeAsync()))
  82. {
  83. await tcs.Task;
  84. }
  85. }
  86. public static async Task ExecuteAsync(this IAsyncScheduler scheduler, Func<CancellationToken, Task> action, CancellationToken token = default(CancellationToken))
  87. {
  88. var tcs = new TaskCompletionSource<object>();
  89. var d = await scheduler.ScheduleAsync(async ct =>
  90. {
  91. try
  92. {
  93. ct.ThrowIfCancellationRequested();
  94. await action(ct).RendezVous(scheduler, ct);
  95. }
  96. catch (OperationCanceledException ex) when (ex.CancellationToken == ct)
  97. {
  98. tcs.TrySetCanceled(ct);
  99. }
  100. catch (Exception ex)
  101. {
  102. tcs.TrySetException(ex);
  103. }
  104. finally
  105. {
  106. tcs.TrySetResult(null);
  107. }
  108. });
  109. using (token.Register(() =>
  110. {
  111. try
  112. {
  113. d.DisposeAsync();
  114. }
  115. finally
  116. {
  117. tcs.TrySetCanceled(token);
  118. }
  119. }))
  120. {
  121. await tcs.Task.ConfigureAwait(false);
  122. }
  123. }
  124. public static async Task<TResult> ExecuteAsync<TResult>(this IAsyncScheduler scheduler, Func<CancellationToken, Task<TResult>> action, CancellationToken token = default(CancellationToken))
  125. {
  126. var tcs = new TaskCompletionSource<TResult>();
  127. var d = await scheduler.ScheduleAsync(async ct =>
  128. {
  129. var res = default(TResult);
  130. try
  131. {
  132. ct.ThrowIfCancellationRequested();
  133. res = await action(ct).RendezVous(scheduler, ct);
  134. }
  135. catch (OperationCanceledException ex) when (ex.CancellationToken == ct)
  136. {
  137. tcs.TrySetCanceled(ct);
  138. }
  139. catch (Exception ex)
  140. {
  141. tcs.TrySetException(ex);
  142. }
  143. finally
  144. {
  145. tcs.TrySetResult(res);
  146. }
  147. });
  148. using (token.Register(() =>
  149. {
  150. try
  151. {
  152. d.DisposeAsync();
  153. }
  154. finally
  155. {
  156. tcs.TrySetCanceled(token);
  157. }
  158. }))
  159. {
  160. return await tcs.Task.ConfigureAwait(false);
  161. }
  162. }
  163. private sealed class RendezVousAwaitable : IAwaitable, IAwaiter // PERF: Can we avoid these allocations?
  164. {
  165. private readonly IAsyncScheduler _scheduler;
  166. private readonly CancellationToken _token;
  167. private bool _done;
  168. private ExceptionDispatchInfo _error;
  169. public RendezVousAwaitable(IAsyncScheduler scheduler, CancellationToken token)
  170. {
  171. _scheduler = scheduler;
  172. _token = token;
  173. }
  174. public bool IsCompleted => _done;
  175. public IAwaiter GetAwaiter() => this;
  176. public void GetResult()
  177. {
  178. if (!_done)
  179. {
  180. throw new InvalidOperationException(); // REVIEW: No support for blocking.
  181. }
  182. if (_error != null)
  183. {
  184. _error.Throw();
  185. }
  186. }
  187. public void OnCompleted(Action continuation)
  188. {
  189. var t = _scheduler.ExecuteAsync(ct =>
  190. {
  191. try
  192. {
  193. continuation();
  194. }
  195. catch (Exception ex)
  196. {
  197. _error = ExceptionDispatchInfo.Capture(ex);
  198. }
  199. finally
  200. {
  201. _done = true;
  202. }
  203. return Task.CompletedTask;
  204. }, _token);
  205. }
  206. }
  207. }
  208. }