TaskExt.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.Runtime.CompilerServices;
  7. namespace System.Threading.Tasks
  8. {
  9. internal static class TaskExt
  10. {
  11. public static readonly Task<bool> Never = new TaskCompletionSource<bool>().Task;
  12. #if USE_FAIR_AND_CHEAPER_MERGE
  13. public static WhenAnyValueTask<T> WhenAny<T>(ValueTask<T>[] tasks)
  14. {
  15. var whenAny = new WhenAnyValueTask<T>(tasks);
  16. whenAny.Start();
  17. return whenAny;
  18. }
  19. // REVIEW: Evaluate options to reduce locking and test performance. Right now, there's one lock
  20. // protecting the queue and the completion delegate field. Care has been taken to limit
  21. // the time under the lock, and the (sequential single) reader path has limited locking.
  22. // Contention due to concurrent completion of tasks could be a concern.
  23. internal sealed class WhenAnyValueTask<T>
  24. {
  25. /// <summary>
  26. /// The tasks to await. Entries in this array may be replaced using <see cref="Replace"/>.
  27. /// </summary>
  28. private readonly ValueTask<T>[] _tasks;
  29. /// <summary>
  30. /// Array of cached delegates passed to awaiters on tasks. These delegates have a closure containing the task index.
  31. /// </summary>
  32. private readonly Action[] _onReady;
  33. /// <summary>
  34. /// Queue of indexes of ready tasks. Awaiting the <see cref="WhenAnyValueTask{T}"/> object will consume this queue in order.
  35. /// </summary>
  36. /// <remarks>
  37. /// A lock on this field is taken when updating the queue or <see cref="_onCompleted"/>.
  38. /// </remarks>
  39. private readonly Queue<int> _ready;
  40. /// <summary>
  41. /// Callback of the current awaiter, if any.
  42. /// </summary>
  43. /// <remarks>
  44. /// Protected for reads and writes by a lock on <see cref="_ready"/>.
  45. /// </remarks>
  46. private Action _onCompleted;
  47. /// <summary>
  48. /// Creates a when any task around the specified tasks.
  49. /// </summary>
  50. /// <param name="tasks">Initial set of tasks to await.</param>
  51. public WhenAnyValueTask(ValueTask<T>[] tasks)
  52. {
  53. _tasks = tasks;
  54. var n = tasks.Length;
  55. _ready = new Queue<int>(n); // NB: Should never exceed this length, so we won't see dynamic realloc.
  56. _onReady = new Action[n];
  57. for (var i = 0; i < n; i++)
  58. {
  59. //
  60. // Cache these delegates, for they have closures (over `this` and `index`), and we need them
  61. // for each replacement of a task, to hook up the continuation.
  62. //
  63. int index = i;
  64. _onReady[index] = () => OnReady(index);
  65. }
  66. }
  67. /// <summary>
  68. /// Start awaiting the tasks. This is done separately from the constructor to avoid complexity dealing
  69. /// with handling concurrent callbacks to the current instance while the constructor is running.
  70. /// </summary>
  71. public void Start()
  72. {
  73. for (var i = 0; i < _tasks.Length; i++)
  74. {
  75. //
  76. // Register a callback with the task, which will enqueue the index of the completed task
  77. // for consumption by awaiters.
  78. //
  79. _tasks[i].ConfigureAwait(false).GetAwaiter().OnCompleted(_onReady[i]);
  80. }
  81. }
  82. /// <summary>
  83. /// Gets an awaiter to await completion of any of the awaited tasks, returning the index of the completed
  84. /// task. When sequentially awaiting the current instance, task indices are yielded in the order that of
  85. /// completion. If all tasks have completed and been observed by awaiting the current instance, the awaiter
  86. /// never returns on a subsequent attempt to await the completion of any task. The caller is responsible
  87. /// for bookkeeping that avoids awaiting this instance more often than the number of pending tasks.
  88. /// </summary>
  89. /// <returns>Awaiter to await completion of any of the awaited task.</returns>
  90. /// <remarks>This class only supports a single active awaiter at any point in time.</remarks>
  91. public Awaiter GetAwaiter() => new Awaiter(this);
  92. /// <summary>
  93. /// Replaces the (completed) task at the specified <paramref name="index"/> and starts awaiting it.
  94. /// </summary>
  95. /// <param name="index">The index of the parameter to replace.</param>
  96. /// <param name="task">The new task to store and await at the specified index.</param>
  97. public void Replace(int index, in ValueTask<T> task)
  98. {
  99. Debug.Assert(_tasks[index].IsCompleted, "A task shouldn't be replaced before it has completed.");
  100. _tasks[index] = task;
  101. task.ConfigureAwait(false).GetAwaiter().OnCompleted(_onReady[index]);
  102. }
  103. /// <summary>
  104. /// Called when any task has completed (thus may run concurrently).
  105. /// </summary>
  106. /// <param name="index">The index of the completed task in <see cref="_tasks"/>.</param>
  107. private void OnReady(int index)
  108. {
  109. Action onCompleted = null;
  110. lock (_ready)
  111. {
  112. //
  113. // Store the index of the task that has completed. This will be picked up from GetResult.
  114. //
  115. _ready.Enqueue(index);
  116. //
  117. // If there's a current awaiter, we'll steal its continuation action and invoke it. By setting
  118. // the continuation action to null, we avoid waking up the same awaiter more than once. Any
  119. // task completions that occur while no awaiter is active will end up being enqueued in _ready.
  120. //
  121. if (_onCompleted != null)
  122. {
  123. onCompleted = _onCompleted;
  124. _onCompleted = null;
  125. }
  126. }
  127. onCompleted?.Invoke();
  128. }
  129. /// <summary>
  130. /// Invoked by awaiters to check if any task has completed, in order to short-circuit the await operation.
  131. /// </summary>
  132. /// <returns><c>true</c> if any task has completed; otherwise, <c>false</c>.</returns>
  133. private bool IsCompleted()
  134. {
  135. // REVIEW: Evaluate options to reduce locking, so the single consuming awaiter has limited contention
  136. // with the multiple concurrent completing enumerator tasks, e.g. using ConcurrentQueue<T>.
  137. lock (_ready)
  138. {
  139. return _ready.Count > 0;
  140. }
  141. }
  142. /// <summary>
  143. /// Gets the index of the earliest task that has completed, used by the awaiter. After stealing an index from
  144. /// the ready queue (by means of awaiting the current instance), the user may chose to replace the task at the
  145. /// returned index by a new task, using the <see cref="Replace"/> method.
  146. /// </summary>
  147. /// <returns>Index of the earliest task that has completed.</returns>
  148. private int GetResult()
  149. {
  150. lock (_ready)
  151. {
  152. return _ready.Dequeue();
  153. }
  154. }
  155. /// <summary>
  156. /// Register a continuation passed by an awaiter.
  157. /// </summary>
  158. /// <param name="action">The continuation action delegate to call when any task is ready.</param>
  159. private void OnCompleted(Action action)
  160. {
  161. bool shouldInvoke = false;
  162. lock (_ready)
  163. {
  164. //
  165. // Check if we have anything ready (which could happen in the short window between checking
  166. // for IsCompleted and calling OnCompleted). If so, we should invoke the action directly. Not
  167. // doing so would be a correctness issue where a task has completed, its index was enqueued,
  168. // but the continuation was never called (unless another task completes and calls the action
  169. // delegate, whose subsequent call to GetResult would pick up the lost index).
  170. //
  171. if (_ready.Count > 0)
  172. {
  173. shouldInvoke = true;
  174. }
  175. else
  176. {
  177. Debug.Assert(_onCompleted == null, "Only a single awaiter is allowed.");
  178. _onCompleted = action;
  179. }
  180. }
  181. //
  182. // NB: We assume this case is rare enough (IsCompleted and OnCompleted happen right after one
  183. // another, and an enqueue should have happened right in between to go from an empty to a
  184. // non-empty queue), so we don't run the risk of triggering a stack overflow due to
  185. // synchronous completion of the await operation (which may be in a loop that awaits the
  186. // current instance again).
  187. //
  188. if (shouldInvoke)
  189. {
  190. action();
  191. }
  192. }
  193. /// <summary>
  194. /// Awaiter type used to await completion of any task.
  195. /// </summary>
  196. public struct Awaiter : INotifyCompletion
  197. {
  198. private readonly WhenAnyValueTask<T> _parent;
  199. public Awaiter(WhenAnyValueTask<T> parent) => _parent = parent;
  200. public bool IsCompleted => _parent.IsCompleted();
  201. public int GetResult() => _parent.GetResult();
  202. public void OnCompleted(Action action) => _parent.OnCompleted(action);
  203. }
  204. }
  205. #endif
  206. }
  207. }