Task.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020
  1. //
  2. // Task.cs
  3. //
  4. // Authors:
  5. // Marek Safar <[email protected]>
  6. // Jérémie Laval <jeremie dot laval at xamarin dot com>
  7. //
  8. // Copyright (c) 2008 Jérémie "Garuma" Laval
  9. // Copyright 2011 Xamarin Inc (http://www.xamarin.com).
  10. //
  11. // Permission is hereby granted, free of charge, to any person obtaining a copy
  12. // of this software and associated documentation files (the "Software"), to deal
  13. // in the Software without restriction, including without limitation the rights
  14. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  15. // copies of the Software, and to permit persons to whom the Software is
  16. // furnished to do so, subject to the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be included in
  19. // all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  22. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  23. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  24. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  25. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  26. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  27. // THE SOFTWARE.
  28. //
  29. //
  30. #if NET_4_0 || MOBILE
  31. using System;
  32. using System.Threading;
  33. using System.Collections.Concurrent;
  34. using System.Collections.Generic;
  35. using System.Runtime.CompilerServices;
  36. namespace System.Threading.Tasks
  37. {
  38. [System.Diagnostics.DebuggerDisplay ("Id = {Id}, Status = {Status}")]
  39. [System.Diagnostics.DebuggerTypeProxy (typeof (TaskDebuggerView))]
  40. public class Task : IDisposable, IAsyncResult
  41. {
  42. const TaskCreationOptions TaskCreationOptionsContinuation = (TaskCreationOptions) (1 << 10);
  43. // With this attribute each thread has its own value so that it's correct for our Schedule code
  44. // and for Parent property.
  45. [System.ThreadStatic]
  46. static Task current;
  47. [System.ThreadStatic]
  48. static Action<Task> childWorkAdder;
  49. Task parent;
  50. static int id = -1;
  51. static readonly TaskFactory defaultFactory = new TaskFactory ();
  52. CountdownEvent childTasks;
  53. int taskId;
  54. TaskCreationOptions taskCreationOptions;
  55. internal TaskScheduler scheduler;
  56. volatile AggregateException exception;
  57. volatile bool exceptionObserved;
  58. ConcurrentQueue<AggregateException> childExceptions;
  59. TaskStatus status;
  60. TaskActionInvoker invoker;
  61. object state;
  62. AtomicBooleanValue executing;
  63. TaskCompletionQueue<IContinuation> continuations;
  64. CancellationToken token;
  65. CancellationTokenRegistration? cancellationRegistration;
  66. internal const TaskCreationOptions WorkerTaskNotSupportedOptions = TaskCreationOptions.LongRunning | TaskCreationOptions.PreferFairness;
  67. const TaskCreationOptions MaxTaskCreationOptions =
  68. #if NET_4_5
  69. TaskCreationOptions.DenyChildAttach | TaskCreationOptions.HideScheduler |
  70. #endif
  71. TaskCreationOptions.PreferFairness | TaskCreationOptions.LongRunning | TaskCreationOptions.AttachedToParent;
  72. public Task (Action action)
  73. : this (action, TaskCreationOptions.None)
  74. {
  75. }
  76. public Task (Action action, TaskCreationOptions creationOptions)
  77. : this (action, CancellationToken.None, creationOptions)
  78. {
  79. }
  80. public Task (Action action, CancellationToken cancellationToken)
  81. : this (action, cancellationToken, TaskCreationOptions.None)
  82. {
  83. }
  84. public Task (Action action, CancellationToken cancellationToken, TaskCreationOptions creationOptions)
  85. : this (TaskActionInvoker.Create (action), null, cancellationToken, creationOptions, current)
  86. {
  87. if (action == null)
  88. throw new ArgumentNullException ("action");
  89. if (creationOptions > MaxTaskCreationOptions || creationOptions < TaskCreationOptions.None)
  90. throw new ArgumentOutOfRangeException ("creationOptions");
  91. }
  92. public Task (Action<object> action, object state)
  93. : this (action, state, TaskCreationOptions.None)
  94. {
  95. }
  96. public Task (Action<object> action, object state, TaskCreationOptions creationOptions)
  97. : this (action, state, CancellationToken.None, creationOptions)
  98. {
  99. }
  100. public Task (Action<object> action, object state, CancellationToken cancellationToken)
  101. : this (action, state, cancellationToken, TaskCreationOptions.None)
  102. {
  103. }
  104. public Task (Action<object> action, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions)
  105. : this (TaskActionInvoker.Create (action), state, cancellationToken, creationOptions, current)
  106. {
  107. if (action == null)
  108. throw new ArgumentNullException ("action");
  109. if (creationOptions > MaxTaskCreationOptions || creationOptions < TaskCreationOptions.None)
  110. throw new ArgumentOutOfRangeException ("creationOptions");
  111. }
  112. internal Task (TaskActionInvoker invoker, object state, CancellationToken cancellationToken,
  113. TaskCreationOptions creationOptions, Task parent)
  114. {
  115. this.invoker = invoker;
  116. this.taskCreationOptions = creationOptions;
  117. this.state = state;
  118. this.taskId = Interlocked.Increment (ref id);
  119. this.status = cancellationToken.IsCancellationRequested ? TaskStatus.Canceled : TaskStatus.Created;
  120. this.token = cancellationToken;
  121. this.parent = parent;
  122. // Process taskCreationOptions
  123. if (CheckTaskOptions (taskCreationOptions, TaskCreationOptions.AttachedToParent) && parent != null)
  124. parent.AddChild ();
  125. if (token.CanBeCanceled)
  126. cancellationRegistration = token.Register (l => ((Task) l).CancelReal (), this);
  127. }
  128. ~Task ()
  129. {
  130. if (exception != null && !exceptionObserved)
  131. throw exception;
  132. }
  133. bool CheckTaskOptions (TaskCreationOptions opt, TaskCreationOptions member)
  134. {
  135. return (opt & member) == member;
  136. }
  137. #region Start
  138. public void Start ()
  139. {
  140. Start (TaskScheduler.Current);
  141. }
  142. public void Start (TaskScheduler scheduler)
  143. {
  144. if (scheduler == null)
  145. throw new ArgumentNullException ("scheduler");
  146. if (status >= TaskStatus.WaitingToRun)
  147. throw new InvalidOperationException ("The Task is not in a valid state to be started.");
  148. if (IsContinuation)
  149. throw new InvalidOperationException ("Start may not be called on a continuation task");
  150. SetupScheduler (scheduler);
  151. Schedule ();
  152. }
  153. internal void SetupScheduler (TaskScheduler scheduler)
  154. {
  155. this.scheduler = scheduler;
  156. Status = TaskStatus.WaitingForActivation;
  157. }
  158. public void RunSynchronously ()
  159. {
  160. RunSynchronously (TaskScheduler.Current);
  161. }
  162. public void RunSynchronously (TaskScheduler scheduler)
  163. {
  164. if (scheduler == null)
  165. throw new ArgumentNullException ("scheduler");
  166. if (Status > TaskStatus.WaitingForActivation)
  167. throw new InvalidOperationException ("The task is not in a valid state to be started");
  168. SetupScheduler (scheduler);
  169. var saveStatus = status;
  170. Status = TaskStatus.WaitingToRun;
  171. try {
  172. if (scheduler.RunInline (this))
  173. return;
  174. } catch (Exception inner) {
  175. throw new TaskSchedulerException (inner);
  176. }
  177. Status = saveStatus;
  178. Start (scheduler);
  179. Wait ();
  180. }
  181. #endregion
  182. #region ContinueWith
  183. public Task ContinueWith (Action<Task> continuationAction)
  184. {
  185. return ContinueWith (continuationAction, TaskContinuationOptions.None);
  186. }
  187. public Task ContinueWith (Action<Task> continuationAction, TaskContinuationOptions continuationOptions)
  188. {
  189. return ContinueWith (continuationAction, CancellationToken.None, continuationOptions, TaskScheduler.Current);
  190. }
  191. public Task ContinueWith (Action<Task> continuationAction, CancellationToken cancellationToken)
  192. {
  193. return ContinueWith (continuationAction, cancellationToken, TaskContinuationOptions.None, TaskScheduler.Current);
  194. }
  195. public Task ContinueWith (Action<Task> continuationAction, TaskScheduler scheduler)
  196. {
  197. return ContinueWith (continuationAction, CancellationToken.None, TaskContinuationOptions.None, scheduler);
  198. }
  199. public Task ContinueWith (Action<Task> continuationAction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
  200. {
  201. if (continuationAction == null)
  202. throw new ArgumentNullException ("continuationAction");
  203. if (scheduler == null)
  204. throw new ArgumentNullException ("scheduler");
  205. return ContinueWith (TaskActionInvoker.Create (continuationAction), cancellationToken, continuationOptions, scheduler);
  206. }
  207. internal Task ContinueWith (TaskActionInvoker invoker, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
  208. {
  209. var continuation = new Task (invoker, null, cancellationToken, GetCreationOptions (continuationOptions), this);
  210. ContinueWithCore (continuation, continuationOptions, scheduler);
  211. return continuation;
  212. }
  213. public Task<TResult> ContinueWith<TResult> (Func<Task, TResult> continuationFunction)
  214. {
  215. return ContinueWith<TResult> (continuationFunction, TaskContinuationOptions.None);
  216. }
  217. public Task<TResult> ContinueWith<TResult> (Func<Task, TResult> continuationFunction, TaskContinuationOptions continuationOptions)
  218. {
  219. return ContinueWith<TResult> (continuationFunction, CancellationToken.None, continuationOptions, TaskScheduler.Current);
  220. }
  221. public Task<TResult> ContinueWith<TResult> (Func<Task, TResult> continuationFunction, CancellationToken cancellationToken)
  222. {
  223. return ContinueWith<TResult> (continuationFunction, cancellationToken, TaskContinuationOptions.None, TaskScheduler.Current);
  224. }
  225. public Task<TResult> ContinueWith<TResult> (Func<Task, TResult> continuationFunction, TaskScheduler scheduler)
  226. {
  227. return ContinueWith<TResult> (continuationFunction, CancellationToken.None, TaskContinuationOptions.None, scheduler);
  228. }
  229. public Task<TResult> ContinueWith<TResult> (Func<Task, TResult> continuationFunction, CancellationToken cancellationToken,
  230. TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
  231. {
  232. if (continuationFunction == null)
  233. throw new ArgumentNullException ("continuationFunction");
  234. if (scheduler == null)
  235. throw new ArgumentNullException ("scheduler");
  236. return ContinueWith<TResult> (TaskActionInvoker.Create (continuationFunction), cancellationToken, continuationOptions, scheduler);
  237. }
  238. internal Task<TResult> ContinueWith<TResult> (TaskActionInvoker invoker, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
  239. {
  240. var continuation = new Task<TResult> (invoker, null, cancellationToken, GetCreationOptions (continuationOptions), this);
  241. ContinueWithCore (continuation, continuationOptions, scheduler);
  242. return continuation;
  243. }
  244. internal void ContinueWithCore (Task continuation, TaskContinuationOptions options, TaskScheduler scheduler)
  245. {
  246. const TaskContinuationOptions wrongRan = TaskContinuationOptions.NotOnRanToCompletion | TaskContinuationOptions.OnlyOnRanToCompletion;
  247. const TaskContinuationOptions wrongCanceled = TaskContinuationOptions.NotOnCanceled | TaskContinuationOptions.OnlyOnCanceled;
  248. const TaskContinuationOptions wrongFaulted = TaskContinuationOptions.NotOnFaulted | TaskContinuationOptions.OnlyOnFaulted;
  249. if (((options & wrongRan) == wrongRan) || ((options & wrongCanceled) == wrongCanceled) || ((options & wrongFaulted) == wrongFaulted))
  250. throw new ArgumentException ("continuationOptions", "Some options are mutually exclusive");
  251. // Already set the scheduler so that user can call Wait and that sort of stuff
  252. continuation.scheduler = scheduler;
  253. continuation.Status = TaskStatus.WaitingForActivation;
  254. continuation.taskCreationOptions |= TaskCreationOptionsContinuation;
  255. ContinueWith (new TaskContinuation (continuation, options));
  256. }
  257. internal void ContinueWith (IContinuation continuation)
  258. {
  259. if (IsCompleted) {
  260. continuation.Execute ();
  261. return;
  262. }
  263. continuations.Add (continuation);
  264. // Retry in case completion was achieved but event adding was too late
  265. if (IsCompleted && continuations.Remove (continuation))
  266. continuation.Execute ();
  267. }
  268. void RemoveContinuation (IContinuation continuation)
  269. {
  270. continuations.Remove (continuation);
  271. }
  272. static internal TaskCreationOptions GetCreationOptions (TaskContinuationOptions kind)
  273. {
  274. TaskCreationOptions options = TaskCreationOptions.None;
  275. if ((kind & TaskContinuationOptions.AttachedToParent) > 0)
  276. options |= TaskCreationOptions.AttachedToParent;
  277. if ((kind & TaskContinuationOptions.PreferFairness) > 0)
  278. options |= TaskCreationOptions.PreferFairness;
  279. if ((kind & TaskContinuationOptions.LongRunning) > 0)
  280. options |= TaskCreationOptions.LongRunning;
  281. return options;
  282. }
  283. #endregion
  284. #region Internal and protected thingies
  285. internal void Schedule ()
  286. {
  287. Status = TaskStatus.WaitingToRun;
  288. // If worker is null it means it is a local one, revert to the old behavior
  289. // If TaskScheduler.Current is not being used, the scheduler was explicitly provided, so we must use that
  290. if (scheduler != TaskScheduler.Current || childWorkAdder == null || CheckTaskOptions (taskCreationOptions, TaskCreationOptions.PreferFairness)) {
  291. scheduler.QueueTask (this);
  292. } else {
  293. /* Like the semantic of the ABP paper describe it, we add ourselves to the bottom
  294. * of our Parent Task's ThreadWorker deque. It's ok to do that since we are in
  295. * the correct Thread during the creation
  296. */
  297. childWorkAdder (this);
  298. }
  299. }
  300. void ThreadStart ()
  301. {
  302. /* Allow scheduler to break fairness of deque ordering without
  303. * breaking its semantic (the task can be executed twice but the
  304. * second time it will return immediately
  305. */
  306. if (!executing.TryRelaxedSet ())
  307. return;
  308. // Disable CancellationToken direct cancellation
  309. if (cancellationRegistration != null) {
  310. cancellationRegistration.Value.Dispose ();
  311. cancellationRegistration = null;
  312. }
  313. current = this;
  314. TaskScheduler.Current = scheduler;
  315. if (!token.IsCancellationRequested) {
  316. status = TaskStatus.Running;
  317. try {
  318. InnerInvoke ();
  319. } catch (OperationCanceledException oce) {
  320. if (token != CancellationToken.None && oce.CancellationToken == token)
  321. CancelReal ();
  322. else
  323. HandleGenericException (oce);
  324. } catch (Exception e) {
  325. HandleGenericException (e);
  326. }
  327. } else {
  328. CancelReal ();
  329. }
  330. Finish ();
  331. }
  332. internal void Execute (Action<Task> childAdder)
  333. {
  334. childWorkAdder = childAdder;
  335. ThreadStart ();
  336. }
  337. internal void AddChild ()
  338. {
  339. if (childTasks == null)
  340. Interlocked.CompareExchange (ref childTasks, new CountdownEvent (1), null);
  341. childTasks.AddCount ();
  342. }
  343. internal void ChildCompleted (AggregateException childEx)
  344. {
  345. if (childEx != null) {
  346. if (childExceptions == null)
  347. Interlocked.CompareExchange (ref childExceptions, new ConcurrentQueue<AggregateException> (), null);
  348. childExceptions.Enqueue (childEx);
  349. }
  350. if (childTasks.Signal () && status == TaskStatus.WaitingForChildrenToComplete) {
  351. Status = TaskStatus.RanToCompletion;
  352. ProcessChildExceptions ();
  353. ProcessCompleteDelegates ();
  354. }
  355. }
  356. void InnerInvoke ()
  357. {
  358. if (IsContinuation) {
  359. invoker.Invoke (parent, state, this);
  360. } else {
  361. invoker.Invoke (this, state, this);
  362. }
  363. }
  364. internal void Finish ()
  365. {
  366. // If there was children created and they all finished, we set the countdown
  367. if (childTasks != null)
  368. childTasks.Signal ();
  369. // Don't override Canceled or Faulted
  370. if (status == TaskStatus.Running) {
  371. if (childTasks == null || childTasks.IsSet)
  372. Status = TaskStatus.RanToCompletion;
  373. else
  374. Status = TaskStatus.WaitingForChildrenToComplete;
  375. }
  376. // Completions are already processed when task is canceled
  377. if (status == TaskStatus.RanToCompletion || status == TaskStatus.Faulted)
  378. ProcessCompleteDelegates ();
  379. // Reset the current thingies
  380. current = null;
  381. TaskScheduler.Current = null;
  382. if (cancellationRegistration.HasValue)
  383. cancellationRegistration.Value.Dispose ();
  384. // Tell parent that we are finished
  385. if (CheckTaskOptions (taskCreationOptions, TaskCreationOptions.AttachedToParent) && parent != null) {
  386. parent.ChildCompleted (this.Exception);
  387. }
  388. }
  389. void ProcessCompleteDelegates ()
  390. {
  391. if (continuations.HasElements) {
  392. IContinuation continuation;
  393. while (continuations.TryGetNextCompletion (out continuation))
  394. continuation.Execute ();
  395. }
  396. }
  397. void ProcessChildExceptions ()
  398. {
  399. if (childExceptions == null)
  400. return;
  401. if (exception == null)
  402. exception = new AggregateException ();
  403. AggregateException childEx;
  404. while (childExceptions.TryDequeue (out childEx))
  405. exception.AddChildException (childEx);
  406. }
  407. #endregion
  408. #region Cancel and Wait related method
  409. internal void CancelReal ()
  410. {
  411. Status = TaskStatus.Canceled;
  412. ProcessCompleteDelegates ();
  413. }
  414. internal void HandleGenericException (Exception e)
  415. {
  416. HandleGenericException (new AggregateException (e));
  417. }
  418. internal void HandleGenericException (AggregateException e)
  419. {
  420. exception = e;
  421. Thread.MemoryBarrier ();
  422. Status = TaskStatus.Faulted;
  423. if (scheduler != null && scheduler.FireUnobservedEvent (exception).Observed)
  424. exceptionObserved = true;
  425. }
  426. public void Wait ()
  427. {
  428. Wait (Timeout.Infinite, CancellationToken.None);
  429. }
  430. public void Wait (CancellationToken cancellationToken)
  431. {
  432. Wait (Timeout.Infinite, cancellationToken);
  433. }
  434. public bool Wait (TimeSpan timeout)
  435. {
  436. return Wait (CheckTimeout (timeout), CancellationToken.None);
  437. }
  438. public bool Wait (int millisecondsTimeout)
  439. {
  440. return Wait (millisecondsTimeout, CancellationToken.None);
  441. }
  442. public bool Wait (int millisecondsTimeout, CancellationToken cancellationToken)
  443. {
  444. if (millisecondsTimeout < -1)
  445. throw new ArgumentOutOfRangeException ("millisecondsTimeout");
  446. bool result = true;
  447. if (!IsCompleted) {
  448. // If the task is ready to be run and we were supposed to wait on it indefinitely, just run it
  449. if (Status == TaskStatus.WaitingToRun && millisecondsTimeout == -1 && scheduler != null)
  450. Execute (null);
  451. if (!IsCompleted) {
  452. var evt = new ManualResetEventSlim ();
  453. var slot = new ManualEventSlot (evt);
  454. try {
  455. ContinueWith (slot);
  456. result = evt.Wait (millisecondsTimeout, cancellationToken);
  457. } finally {
  458. if (!result)
  459. RemoveContinuation (slot);
  460. evt.Dispose ();
  461. }
  462. }
  463. }
  464. if (IsCanceled)
  465. throw new AggregateException (new TaskCanceledException (this));
  466. if (exception != null)
  467. throw exception;
  468. return result;
  469. }
  470. public static void WaitAll (params Task[] tasks)
  471. {
  472. WaitAll (tasks, Timeout.Infinite, CancellationToken.None);
  473. }
  474. public static void WaitAll (Task[] tasks, CancellationToken cancellationToken)
  475. {
  476. WaitAll (tasks, Timeout.Infinite, cancellationToken);
  477. }
  478. public static bool WaitAll (Task[] tasks, TimeSpan timeout)
  479. {
  480. return WaitAll (tasks, CheckTimeout (timeout), CancellationToken.None);
  481. }
  482. public static bool WaitAll (Task[] tasks, int millisecondsTimeout)
  483. {
  484. return WaitAll (tasks, millisecondsTimeout, CancellationToken.None);
  485. }
  486. public static bool WaitAll (Task[] tasks, int millisecondsTimeout, CancellationToken cancellationToken)
  487. {
  488. if (tasks == null)
  489. throw new ArgumentNullException ("tasks");
  490. bool result = true;
  491. foreach (var t in tasks) {
  492. if (t == null)
  493. throw new ArgumentNullException ("tasks", "the tasks argument contains a null element");
  494. result &= t.Status == TaskStatus.RanToCompletion;
  495. }
  496. if (!result) {
  497. var evt = new CountdownEvent (tasks.Length);
  498. var slot = new CountdownEventSlot (evt);
  499. try {
  500. foreach (var t in tasks)
  501. t.ContinueWith (slot);
  502. result = evt.Wait (millisecondsTimeout, cancellationToken);
  503. } finally {
  504. List<Exception> exceptions = null;
  505. foreach (var t in tasks) {
  506. if (result) {
  507. if (t.Status == TaskStatus.RanToCompletion)
  508. continue;
  509. if (exceptions == null)
  510. exceptions = new List<Exception> ();
  511. if (t.Exception != null)
  512. exceptions.AddRange (t.Exception.InnerExceptions);
  513. else
  514. exceptions.Add (new TaskCanceledException (t));
  515. } else {
  516. t.RemoveContinuation (slot);
  517. }
  518. }
  519. evt.Dispose ();
  520. if (exceptions != null)
  521. throw new AggregateException (exceptions);
  522. }
  523. }
  524. return result;
  525. }
  526. public static int WaitAny (params Task[] tasks)
  527. {
  528. return WaitAny (tasks, Timeout.Infinite, CancellationToken.None);
  529. }
  530. public static int WaitAny (Task[] tasks, TimeSpan timeout)
  531. {
  532. return WaitAny (tasks, CheckTimeout (timeout));
  533. }
  534. public static int WaitAny (Task[] tasks, int millisecondsTimeout)
  535. {
  536. return WaitAny (tasks, millisecondsTimeout, CancellationToken.None);
  537. }
  538. public static int WaitAny (Task[] tasks, CancellationToken cancellationToken)
  539. {
  540. return WaitAny (tasks, Timeout.Infinite, cancellationToken);
  541. }
  542. public static int WaitAny (Task[] tasks, int millisecondsTimeout, CancellationToken cancellationToken)
  543. {
  544. if (tasks == null)
  545. throw new ArgumentNullException ("tasks");
  546. if (millisecondsTimeout < -1)
  547. throw new ArgumentOutOfRangeException ("millisecondsTimeout");
  548. CheckForNullTasks (tasks);
  549. if (tasks.Length > 0) {
  550. var evt = new ManualResetEventSlim ();
  551. var slot = new ManualEventSlot (evt);
  552. bool result = false;
  553. try {
  554. for (int i = 0; i < tasks.Length; i++) {
  555. var t = tasks[i];
  556. if (t.IsCompleted)
  557. return i;
  558. t.ContinueWith (slot);
  559. }
  560. if (!(result = evt.Wait (millisecondsTimeout, cancellationToken)))
  561. return -1;
  562. } finally {
  563. if (!result)
  564. foreach (var t in tasks)
  565. t.RemoveContinuation (slot);
  566. evt.Dispose ();
  567. }
  568. }
  569. int firstFinished = -1;
  570. for (int i = 0; i < tasks.Length; i++) {
  571. var t = tasks[i];
  572. if (t.IsCompleted) {
  573. firstFinished = i;
  574. break;
  575. }
  576. }
  577. return firstFinished;
  578. }
  579. static int CheckTimeout (TimeSpan timeout)
  580. {
  581. try {
  582. return checked ((int)timeout.TotalMilliseconds);
  583. } catch (System.OverflowException) {
  584. throw new ArgumentOutOfRangeException ("timeout");
  585. }
  586. }
  587. static void CheckForNullTasks (Task[] tasks)
  588. {
  589. foreach (var t in tasks)
  590. if (t == null)
  591. throw new ArgumentNullException ("tasks", "the tasks argument contains a null element");
  592. }
  593. #endregion
  594. #region Dispose
  595. public void Dispose ()
  596. {
  597. Dispose (true);
  598. }
  599. protected virtual void Dispose (bool disposing)
  600. {
  601. if (!IsCompleted)
  602. throw new InvalidOperationException ("A task may only be disposed if it is in a completion state");
  603. // Set action to null so that the GC can collect the delegate and thus
  604. // any big object references that the user might have captured in a anonymous method
  605. if (disposing) {
  606. invoker = null;
  607. state = null;
  608. if (cancellationRegistration != null)
  609. cancellationRegistration.Value.Dispose ();
  610. }
  611. }
  612. #endregion
  613. #if NET_4_5
  614. public ConfiguredTaskAwaitable ConfigureAwait (bool continueOnCapturedContext)
  615. {
  616. return new ConfiguredTaskAwaitable (this, continueOnCapturedContext);
  617. }
  618. public Task ContinueWith (Action<Task, object> continuationAction, object state)
  619. {
  620. return ContinueWith (continuationAction, state, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Current);
  621. }
  622. public Task ContinueWith (Action<Task, object> continuationAction, object state, CancellationToken cancellationToken)
  623. {
  624. return ContinueWith (continuationAction, state, cancellationToken, TaskContinuationOptions.None, TaskScheduler.Current);
  625. }
  626. public Task ContinueWith (Action<Task, object> continuationAction, object state, TaskContinuationOptions continuationOptions)
  627. {
  628. return ContinueWith (continuationAction, state, CancellationToken.None, continuationOptions, TaskScheduler.Current);
  629. }
  630. public Task ContinueWith (Action<Task, object> continuationAction, object state, TaskScheduler scheduler)
  631. {
  632. return ContinueWith (continuationAction, state, CancellationToken.None, TaskContinuationOptions.None, scheduler);
  633. }
  634. public Task ContinueWith (Action<Task, object> continuationAction, object state, CancellationToken cancellationToken,
  635. TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
  636. {
  637. if (continuationAction == null)
  638. throw new ArgumentNullException ("continuationAction");
  639. if (scheduler == null)
  640. throw new ArgumentNullException ("scheduler");
  641. Task continuation = new Task (TaskActionInvoker.Create (continuationAction),
  642. state, cancellationToken,
  643. GetCreationOptions (continuationOptions),
  644. this);
  645. ContinueWithCore (continuation, continuationOptions, scheduler);
  646. return continuation;
  647. }
  648. public Task<TResult> ContinueWith<TResult> (Func<Task, object, TResult> continuationFunction, object state)
  649. {
  650. return ContinueWith<TResult> (continuationFunction, state, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Current);
  651. }
  652. public Task<TResult> ContinueWith<TResult> (Func<Task, object, TResult> continuationFunction, object state, TaskContinuationOptions continuationOptions)
  653. {
  654. return ContinueWith<TResult> (continuationFunction, state, CancellationToken.None, continuationOptions, TaskScheduler.Current);
  655. }
  656. public Task<TResult> ContinueWith<TResult> (Func<Task, object, TResult> continuationFunction, object state, CancellationToken cancellationToken)
  657. {
  658. return ContinueWith<TResult> (continuationFunction, state, cancellationToken, TaskContinuationOptions.None, TaskScheduler.Current);
  659. }
  660. public Task<TResult> ContinueWith<TResult> (Func<Task, object, TResult> continuationFunction, object state, TaskScheduler scheduler)
  661. {
  662. return ContinueWith<TResult> (continuationFunction, state, CancellationToken.None, TaskContinuationOptions.None, scheduler);
  663. }
  664. public Task<TResult> ContinueWith<TResult> (Func<Task, object, TResult> continuationFunction, object state, CancellationToken cancellationToken,
  665. TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
  666. {
  667. if (continuationFunction == null)
  668. throw new ArgumentNullException ("continuationFunction");
  669. if (scheduler == null)
  670. throw new ArgumentNullException ("scheduler");
  671. var t = new Task<TResult> (TaskActionInvoker.Create (continuationFunction),
  672. state,
  673. cancellationToken,
  674. GetCreationOptions (continuationOptions),
  675. this);
  676. ContinueWithCore (t, continuationOptions, scheduler);
  677. return t;
  678. }
  679. public static Task<TResult> FromResult<TResult> (TResult result)
  680. {
  681. var tcs = new TaskCompletionSource<TResult> ();
  682. tcs.SetResult (result);
  683. return tcs.Task;
  684. }
  685. public TaskAwaiter GetAwaiter ()
  686. {
  687. return new TaskAwaiter (this);
  688. }
  689. public static Task Run (Action action)
  690. {
  691. return Run (action, CancellationToken.None);
  692. }
  693. public static Task Run (Action action, CancellationToken cancellationToken)
  694. {
  695. if (cancellationToken.IsCancellationRequested)
  696. return TaskConstants.Canceled;
  697. var t = new Task (action, cancellationToken, TaskCreationOptions.DenyChildAttach);
  698. t.Start ();
  699. return t;
  700. }
  701. public static Task Run (Func<Task> function)
  702. {
  703. return Run (function, CancellationToken.None);
  704. }
  705. public static Task Run (Func<Task> function, CancellationToken cancellationToken)
  706. {
  707. if (cancellationToken.IsCancellationRequested)
  708. return TaskConstants.Canceled;
  709. var t = new Task<Task> (function, cancellationToken);
  710. t.Start ();
  711. return t;
  712. }
  713. public static Task<TResult> Run<TResult> (Func<TResult> function)
  714. {
  715. return Run (function, CancellationToken.None);
  716. }
  717. public static Task<TResult> Run<TResult> (Func<TResult> function, CancellationToken cancellationToken)
  718. {
  719. if (cancellationToken.IsCancellationRequested)
  720. return TaskConstants<TResult>.Canceled;
  721. var t = new Task<TResult> (function, cancellationToken, TaskCreationOptions.DenyChildAttach);
  722. t.Start ();
  723. return t;
  724. }
  725. public static Task<TResult> Run<TResult> (Func<Task<TResult>> function)
  726. {
  727. return Run (function, CancellationToken.None);
  728. }
  729. public static Task<TResult> Run<TResult> (Func<Task<TResult>> function, CancellationToken cancellationToken)
  730. {
  731. if (cancellationToken.IsCancellationRequested)
  732. return TaskConstants<TResult>.Canceled;
  733. var t = Task<Task<TResult>>.Factory.StartNew (function, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
  734. return GetTaskResult (t);
  735. }
  736. async static Task<TResult> GetTaskResult<TResult> (Task<Task<TResult>> task)
  737. {
  738. var r = await task.ConfigureAwait (false);
  739. return r.Result;
  740. }
  741. public static YieldAwaitable Yield ()
  742. {
  743. return new YieldAwaitable ();
  744. }
  745. #endif
  746. #region Properties
  747. public static TaskFactory Factory {
  748. get {
  749. return defaultFactory;
  750. }
  751. }
  752. public static int? CurrentId {
  753. get {
  754. Task t = current;
  755. return t == null ? (int?)null : t.Id;
  756. }
  757. }
  758. public AggregateException Exception {
  759. get {
  760. exceptionObserved = true;
  761. return exception;
  762. }
  763. internal set {
  764. exception = value;
  765. }
  766. }
  767. public bool IsCanceled {
  768. get {
  769. return status == TaskStatus.Canceled;
  770. }
  771. }
  772. public bool IsCompleted {
  773. get {
  774. return status >= TaskStatus.RanToCompletion;
  775. }
  776. }
  777. public bool IsFaulted {
  778. get {
  779. return status == TaskStatus.Faulted;
  780. }
  781. }
  782. public TaskCreationOptions CreationOptions {
  783. get {
  784. return taskCreationOptions & MaxTaskCreationOptions;
  785. }
  786. }
  787. public TaskStatus Status {
  788. get {
  789. return status;
  790. }
  791. internal set {
  792. status = value;
  793. Thread.MemoryBarrier ();
  794. }
  795. }
  796. public object AsyncState {
  797. get {
  798. return state;
  799. }
  800. }
  801. bool IAsyncResult.CompletedSynchronously {
  802. get {
  803. return true;
  804. }
  805. }
  806. WaitHandle IAsyncResult.AsyncWaitHandle {
  807. get {
  808. return null;
  809. }
  810. }
  811. public int Id {
  812. get {
  813. return taskId;
  814. }
  815. }
  816. bool IsContinuation {
  817. get {
  818. return (taskCreationOptions & TaskCreationOptionsContinuation) != 0;
  819. }
  820. }
  821. internal Task Parent {
  822. get {
  823. return parent;
  824. }
  825. }
  826. internal string DisplayActionMethod {
  827. get {
  828. Delegate d = invoker.Action;
  829. return d == null ? "<none>" : d.Method.ToString ();
  830. }
  831. }
  832. #endregion
  833. }
  834. }
  835. #endif