Task.cs 25 KB

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