2
0

Task.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901
  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}, Method = {DisplayActionMethod}")]
  31. // [System.Diagnostics.DebuggerTypeProxy ("System.Threading.Tasks.SystemThreadingTasks_TaskDebugView")]
  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 (Status > TaskStatus.WaitingForActivation)
  148. throw new InvalidOperationException ("The task is not in a valid state to be started");
  149. SetupScheduler (scheduler);
  150. status = TaskStatus.WaitingToRun;
  151. if (scheduler.RunInline (this))
  152. return;
  153. Start (scheduler);
  154. Wait ();
  155. }
  156. #endregion
  157. #region ContinueWith
  158. public Task ContinueWith (Action<Task> continuationAction)
  159. {
  160. return ContinueWith (continuationAction, TaskContinuationOptions.None);
  161. }
  162. public Task ContinueWith (Action<Task> continuationAction, TaskContinuationOptions continuationOptions)
  163. {
  164. return ContinueWith (continuationAction, CancellationToken.None, continuationOptions, TaskScheduler.Current);
  165. }
  166. public Task ContinueWith (Action<Task> continuationAction, CancellationToken cancellationToken)
  167. {
  168. return ContinueWith (continuationAction, cancellationToken, TaskContinuationOptions.None, TaskScheduler.Current);
  169. }
  170. public Task ContinueWith (Action<Task> continuationAction, TaskScheduler scheduler)
  171. {
  172. return ContinueWith (continuationAction, CancellationToken.None, TaskContinuationOptions.None, scheduler);
  173. }
  174. public Task ContinueWith (Action<Task> continuationAction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
  175. {
  176. Task continuation = new Task ((o) => continuationAction ((Task)o),
  177. this,
  178. cancellationToken,
  179. GetCreationOptions (continuationOptions),
  180. this);
  181. ContinueWithCore (continuation, continuationOptions, scheduler);
  182. return continuation;
  183. }
  184. public Task<TResult> ContinueWith<TResult> (Func<Task, TResult> continuationFunction)
  185. {
  186. return ContinueWith<TResult> (continuationFunction, TaskContinuationOptions.None);
  187. }
  188. public Task<TResult> ContinueWith<TResult> (Func<Task, TResult> continuationFunction, TaskContinuationOptions continuationOptions)
  189. {
  190. return ContinueWith<TResult> (continuationFunction, CancellationToken.None, continuationOptions, TaskScheduler.Current);
  191. }
  192. public Task<TResult> ContinueWith<TResult> (Func<Task, TResult> continuationFunction, CancellationToken cancellationToken)
  193. {
  194. return ContinueWith<TResult> (continuationFunction, cancellationToken, TaskContinuationOptions.None, TaskScheduler.Current);
  195. }
  196. public Task<TResult> ContinueWith<TResult> (Func<Task, TResult> continuationFunction, TaskScheduler scheduler)
  197. {
  198. return ContinueWith<TResult> (continuationFunction, CancellationToken.None, TaskContinuationOptions.None, scheduler);
  199. }
  200. public Task<TResult> ContinueWith<TResult> (Func<Task, TResult> continuationFunction, CancellationToken cancellationToken,
  201. TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
  202. {
  203. if (continuationFunction == null)
  204. throw new ArgumentNullException ("continuationFunction");
  205. if (scheduler == null)
  206. throw new ArgumentNullException ("scheduler");
  207. Task<TResult> t = new Task<TResult> ((o) => continuationFunction ((Task)o),
  208. this,
  209. cancellationToken,
  210. GetCreationOptions (continuationOptions),
  211. this);
  212. ContinueWithCore (t, continuationOptions, scheduler);
  213. return t;
  214. }
  215. internal void ContinueWithCore (Task continuation, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
  216. {
  217. ContinueWithCore (continuation, continuationOptions, scheduler, null);
  218. }
  219. internal void ContinueWithCore (Task continuation, TaskContinuationOptions kind,
  220. TaskScheduler scheduler, Func<bool> predicate)
  221. {
  222. // Already set the scheduler so that user can call Wait and that sort of stuff
  223. continuation.scheduler = scheduler;
  224. continuation.schedWait.Set ();
  225. continuation.status = TaskStatus.WaitingForActivation;
  226. AtomicBoolean launched = new AtomicBoolean ();
  227. EventHandler action = delegate (object sender, EventArgs e) {
  228. if (launched.TryRelaxedSet ()) {
  229. if (predicate != null && !predicate ())
  230. return;
  231. if (!ContinuationStatusCheck (kind)) {
  232. continuation.CancelReal ();
  233. continuation.Dispose ();
  234. return;
  235. }
  236. CheckAndSchedule (continuation, kind, scheduler, sender == null);
  237. }
  238. };
  239. if (IsCompleted) {
  240. action (null, EventArgs.Empty);
  241. return;
  242. }
  243. if (completed == null)
  244. Interlocked.CompareExchange (ref completed, new ConcurrentQueue<EventHandler> (), null);
  245. completed.Enqueue (action);
  246. // Retry in case completion was achieved but event adding was too late
  247. if (IsCompleted)
  248. action (null, EventArgs.Empty);
  249. }
  250. bool ContinuationStatusCheck (TaskContinuationOptions kind)
  251. {
  252. if (kind == TaskContinuationOptions.None)
  253. return true;
  254. int kindCode = (int)kind;
  255. if (kindCode >= ((int)TaskContinuationOptions.NotOnRanToCompletion)) {
  256. // Remove other options
  257. kind &= ~(TaskContinuationOptions.PreferFairness
  258. | TaskContinuationOptions.LongRunning
  259. | TaskContinuationOptions.AttachedToParent
  260. | TaskContinuationOptions.ExecuteSynchronously);
  261. if (status == TaskStatus.Canceled) {
  262. if (kind == TaskContinuationOptions.NotOnCanceled)
  263. return false;
  264. if (kind == TaskContinuationOptions.OnlyOnFaulted)
  265. return false;
  266. if (kind == TaskContinuationOptions.OnlyOnRanToCompletion)
  267. return false;
  268. } else if (status == TaskStatus.Faulted) {
  269. if (kind == TaskContinuationOptions.NotOnFaulted)
  270. return false;
  271. if (kind == TaskContinuationOptions.OnlyOnCanceled)
  272. return false;
  273. if (kind == TaskContinuationOptions.OnlyOnRanToCompletion)
  274. return false;
  275. } else if (status == TaskStatus.RanToCompletion) {
  276. if (kind == TaskContinuationOptions.NotOnRanToCompletion)
  277. return false;
  278. if (kind == TaskContinuationOptions.OnlyOnFaulted)
  279. return false;
  280. if (kind == TaskContinuationOptions.OnlyOnCanceled)
  281. return false;
  282. }
  283. }
  284. return true;
  285. }
  286. void CheckAndSchedule (Task continuation, TaskContinuationOptions options, TaskScheduler scheduler, bool fromCaller)
  287. {
  288. if ((options & TaskContinuationOptions.ExecuteSynchronously) > 0)
  289. continuation.RunSynchronously (scheduler);
  290. else
  291. continuation.Start (scheduler);
  292. }
  293. internal TaskCreationOptions GetCreationOptions (TaskContinuationOptions kind)
  294. {
  295. TaskCreationOptions options = TaskCreationOptions.None;
  296. if ((kind & TaskContinuationOptions.AttachedToParent) > 0)
  297. options |= TaskCreationOptions.AttachedToParent;
  298. if ((kind & TaskContinuationOptions.PreferFairness) > 0)
  299. options |= TaskCreationOptions.PreferFairness;
  300. if ((kind & TaskContinuationOptions.LongRunning) > 0)
  301. options |= TaskCreationOptions.LongRunning;
  302. return options;
  303. }
  304. #endregion
  305. #region Internal and protected thingies
  306. internal void Schedule ()
  307. {
  308. status = TaskStatus.WaitingToRun;
  309. // If worker is null it means it is a local one, revert to the old behavior
  310. // If TaskScheduler.Current is not being used, the scheduler was explicitly provided, so we must use that
  311. if (scheduler != TaskScheduler.Current || childWorkAdder == null || CheckTaskOptions (taskCreationOptions, TaskCreationOptions.PreferFairness)) {
  312. scheduler.QueueTask (this);
  313. } else {
  314. /* Like the semantic of the ABP paper describe it, we add ourselves to the bottom
  315. * of our Parent Task's ThreadWorker deque. It's ok to do that since we are in
  316. * the correct Thread during the creation
  317. */
  318. childWorkAdder (this);
  319. }
  320. }
  321. void ThreadStart ()
  322. {
  323. /* Allow scheduler to break fairness of deque ordering without
  324. * breaking its semantic (the task can be executed twice but the
  325. * second time it will return immediately
  326. */
  327. if (!executing.TryRelaxedSet ())
  328. return;
  329. current = this;
  330. TaskScheduler.Current = scheduler;
  331. if (!token.IsCancellationRequested) {
  332. status = TaskStatus.Running;
  333. try {
  334. InnerInvoke ();
  335. } catch (OperationCanceledException oce) {
  336. if (token != CancellationToken.None && oce.CancellationToken == token)
  337. CancelReal ();
  338. else
  339. HandleGenericException (oce);
  340. } catch (Exception e) {
  341. HandleGenericException (e);
  342. }
  343. } else {
  344. CancelReal ();
  345. }
  346. Finish ();
  347. }
  348. internal void Execute (Action<Task> childAdder)
  349. {
  350. childWorkAdder = childAdder;
  351. ThreadStart ();
  352. }
  353. internal void AddChild ()
  354. {
  355. childTasks.AddCount ();
  356. }
  357. internal void ChildCompleted (AggregateException childEx)
  358. {
  359. if (childEx != null) {
  360. if (childExceptions == null)
  361. Interlocked.CompareExchange (ref childExceptions, new ConcurrentQueue<AggregateException> (), null);
  362. childExceptions.Enqueue (childEx);
  363. }
  364. if (childTasks.Signal () && status == TaskStatus.WaitingForChildrenToComplete) {
  365. status = TaskStatus.RanToCompletion;
  366. ProcessChildExceptions ();
  367. ProcessCompleteDelegates ();
  368. }
  369. }
  370. internal virtual void InnerInvoke ()
  371. {
  372. if (action == null && simpleAction != null)
  373. simpleAction ();
  374. else if (action != null)
  375. action (state);
  376. // Set action to null so that the GC can collect the delegate and thus
  377. // any big object references that the user might have captured in an anonymous method
  378. action = null;
  379. simpleAction = null;
  380. state = null;
  381. }
  382. internal void Finish ()
  383. {
  384. // If there wasn't any child created in the task we set the CountdownEvent
  385. childTasks.Signal ();
  386. // Don't override Canceled or Faulted
  387. if (status == TaskStatus.Running) {
  388. if (childTasks.IsSet)
  389. status = TaskStatus.RanToCompletion;
  390. else
  391. status = TaskStatus.WaitingForChildrenToComplete;
  392. }
  393. if (status != TaskStatus.WaitingForChildrenToComplete)
  394. ProcessCompleteDelegates ();
  395. // Reset the current thingies
  396. current = null;
  397. TaskScheduler.Current = null;
  398. // Tell parent that we are finished
  399. if (CheckTaskOptions (taskCreationOptions, TaskCreationOptions.AttachedToParent) && parent != null) {
  400. parent.ChildCompleted (this.Exception);
  401. }
  402. }
  403. void ProcessCompleteDelegates ()
  404. {
  405. if (completed == null)
  406. return;
  407. EventHandler handler;
  408. while (completed.TryDequeue (out handler))
  409. handler (this, EventArgs.Empty);
  410. }
  411. void ProcessChildExceptions ()
  412. {
  413. if (childExceptions == null)
  414. return;
  415. if (exception == null)
  416. exception = new AggregateException ();
  417. AggregateException childEx;
  418. while (childExceptions.TryDequeue (out childEx))
  419. exception.AddChildException (childEx);
  420. }
  421. #endregion
  422. #region Cancel and Wait related method
  423. internal void CancelReal ()
  424. {
  425. status = TaskStatus.Canceled;
  426. }
  427. internal void HandleGenericException (Exception e)
  428. {
  429. HandleGenericException (new AggregateException (e));
  430. }
  431. internal void HandleGenericException (AggregateException e)
  432. {
  433. exception = e;
  434. Thread.MemoryBarrier ();
  435. status = TaskStatus.Faulted;
  436. if (scheduler != null && scheduler.FireUnobservedEvent (exception).Observed)
  437. exceptionObserved = true;
  438. }
  439. public void Wait ()
  440. {
  441. if (scheduler == null)
  442. schedWait.Wait ();
  443. if (!IsCompleted)
  444. scheduler.ParticipateUntil (this);
  445. if (exception != null)
  446. throw exception;
  447. if (IsCanceled)
  448. throw new AggregateException (new TaskCanceledException (this));
  449. }
  450. public void Wait (CancellationToken cancellationToken)
  451. {
  452. Wait (-1, cancellationToken);
  453. }
  454. public bool Wait (TimeSpan timeout)
  455. {
  456. return Wait (CheckTimeout (timeout), CancellationToken.None);
  457. }
  458. public bool Wait (int millisecondsTimeout)
  459. {
  460. return Wait (millisecondsTimeout, CancellationToken.None);
  461. }
  462. public bool Wait (int millisecondsTimeout, CancellationToken cancellationToken)
  463. {
  464. if (millisecondsTimeout < -1)
  465. throw new ArgumentOutOfRangeException ("millisecondsTimeout");
  466. if (millisecondsTimeout == -1 && token == CancellationToken.None) {
  467. Wait ();
  468. return true;
  469. }
  470. Watch watch = Watch.StartNew ();
  471. if (scheduler == null) {
  472. schedWait.Wait (millisecondsTimeout, cancellationToken);
  473. millisecondsTimeout = ComputeTimeout (millisecondsTimeout, watch);
  474. }
  475. ManualResetEventSlim predicateEvt = new ManualResetEventSlim (false);
  476. if (cancellationToken != CancellationToken.None) {
  477. cancellationToken.Register (predicateEvt.Set);
  478. cancellationToken.ThrowIfCancellationRequested ();
  479. }
  480. bool result = scheduler.ParticipateUntil (this, predicateEvt, millisecondsTimeout);
  481. if (exception != null)
  482. throw exception;
  483. if (IsCanceled)
  484. throw new AggregateException (new TaskCanceledException (this));
  485. return !result;
  486. }
  487. public static void WaitAll (params Task[] tasks)
  488. {
  489. if (tasks == null)
  490. throw new ArgumentNullException ("tasks");
  491. foreach (var t in tasks) {
  492. if (t == null)
  493. throw new ArgumentNullException ("tasks", "the tasks argument contains a null element");
  494. t.Wait ();
  495. }
  496. }
  497. public static void WaitAll (Task[] tasks, CancellationToken cancellationToken)
  498. {
  499. if (tasks == null)
  500. throw new ArgumentNullException ("tasks");
  501. foreach (var t in tasks) {
  502. if (t == null)
  503. throw new ArgumentNullException ("tasks", "the tasks argument contains a null element");
  504. t.Wait (cancellationToken);
  505. }
  506. }
  507. public static bool WaitAll (Task[] tasks, TimeSpan timeout)
  508. {
  509. if (tasks == null)
  510. throw new ArgumentNullException ("tasks");
  511. bool result = true;
  512. foreach (var t in tasks) {
  513. if (t == null)
  514. throw new ArgumentNullException ("tasks", "the tasks argument contains a null element");
  515. result &= t.Wait (timeout);
  516. }
  517. return result;
  518. }
  519. public static bool WaitAll (Task[] tasks, int millisecondsTimeout)
  520. {
  521. if (tasks == null)
  522. throw new ArgumentNullException ("tasks");
  523. bool result = true;
  524. foreach (var t in tasks) {
  525. if (t == null)
  526. throw new ArgumentNullException ("tasks", "the tasks argument contains a null element");
  527. result &= t.Wait (millisecondsTimeout);
  528. }
  529. return result;
  530. }
  531. public static bool WaitAll (Task[] tasks, int millisecondsTimeout, CancellationToken cancellationToken)
  532. {
  533. if (tasks == null)
  534. throw new ArgumentNullException ("tasks");
  535. bool result = true;
  536. foreach (var t in tasks) {
  537. if (t == null)
  538. throw new ArgumentNullException ("tasks", "the tasks argument contains a null element");
  539. result &= t.Wait (millisecondsTimeout, cancellationToken);
  540. }
  541. return result;
  542. }
  543. public static int WaitAny (params Task[] tasks)
  544. {
  545. return WaitAny (tasks, -1, CancellationToken.None);
  546. }
  547. public static int WaitAny (Task[] tasks, TimeSpan timeout)
  548. {
  549. return WaitAny (tasks, CheckTimeout (timeout));
  550. }
  551. public static int WaitAny (Task[] tasks, int millisecondsTimeout)
  552. {
  553. if (millisecondsTimeout < -1)
  554. throw new ArgumentOutOfRangeException ("millisecondsTimeout");
  555. if (millisecondsTimeout == -1)
  556. return WaitAny (tasks);
  557. return WaitAny (tasks, millisecondsTimeout, CancellationToken.None);
  558. }
  559. public static int WaitAny (Task[] tasks, CancellationToken cancellationToken)
  560. {
  561. return WaitAny (tasks, -1, cancellationToken);
  562. }
  563. public static int WaitAny (Task[] tasks, int millisecondsTimeout, CancellationToken cancellationToken)
  564. {
  565. if (tasks == null)
  566. throw new ArgumentNullException ("tasks");
  567. if (tasks.Length == 0)
  568. throw new ArgumentException ("tasks is empty", "tasks");
  569. if (tasks.Length == 1) {
  570. tasks[0].Wait (millisecondsTimeout, cancellationToken);
  571. return 0;
  572. }
  573. int numFinished = 0;
  574. int indexFirstFinished = -1;
  575. int index = 0;
  576. TaskScheduler sched = null;
  577. Task task = null;
  578. Watch watch = Watch.StartNew ();
  579. ManualResetEventSlim predicateEvt = new ManualResetEventSlim (false);
  580. foreach (Task t in tasks) {
  581. int indexResult = index++;
  582. t.ContinueWith (delegate {
  583. if (numFinished >= 1)
  584. return;
  585. int result = Interlocked.Increment (ref numFinished);
  586. // Check if we are the first to have finished
  587. if (result == 1)
  588. indexFirstFinished = indexResult;
  589. // Stop waiting
  590. predicateEvt.Set ();
  591. }, TaskContinuationOptions.ExecuteSynchronously);
  592. if (sched == null && t.scheduler != null) {
  593. task = t;
  594. sched = t.scheduler;
  595. }
  596. }
  597. // If none of task have a scheduler we are forced to wait for at least one to start
  598. if (sched == null) {
  599. var handles = Array.ConvertAll (tasks, t => t.schedWait.WaitHandle);
  600. int shandle = -1;
  601. if ((shandle = WaitHandle.WaitAny (handles, millisecondsTimeout)) == WaitHandle.WaitTimeout)
  602. return -1;
  603. sched = tasks[shandle].scheduler;
  604. task = tasks[shandle];
  605. millisecondsTimeout = ComputeTimeout (millisecondsTimeout, watch);
  606. }
  607. // One task already finished
  608. if (indexFirstFinished != -1)
  609. return indexFirstFinished;
  610. if (cancellationToken != CancellationToken.None) {
  611. cancellationToken.Register (predicateEvt.Set);
  612. cancellationToken.ThrowIfCancellationRequested ();
  613. }
  614. sched.ParticipateUntil (task, predicateEvt, millisecondsTimeout);
  615. // Index update is still not done
  616. if (indexFirstFinished == -1) {
  617. SpinWait wait = new SpinWait ();
  618. while (indexFirstFinished == -1)
  619. wait.SpinOnce ();
  620. }
  621. return indexFirstFinished;
  622. }
  623. static int CheckTimeout (TimeSpan timeout)
  624. {
  625. try {
  626. return checked ((int)timeout.TotalMilliseconds);
  627. } catch (System.OverflowException) {
  628. throw new ArgumentOutOfRangeException ("timeout");
  629. }
  630. }
  631. static int ComputeTimeout (int millisecondsTimeout, Watch watch)
  632. {
  633. return millisecondsTimeout == -1 ? -1 : (int)Math.Max (watch.ElapsedMilliseconds - millisecondsTimeout, 1);
  634. }
  635. #endregion
  636. #region Dispose
  637. public void Dispose ()
  638. {
  639. Dispose (true);
  640. }
  641. protected virtual void Dispose (bool disposing)
  642. {
  643. if (!IsCompleted)
  644. throw new InvalidOperationException ("A task may only be disposed if it is in a completion state");
  645. // Set action to null so that the GC can collect the delegate and thus
  646. // any big object references that the user might have captured in a anonymous method
  647. if (disposing) {
  648. action = null;
  649. state = null;
  650. }
  651. }
  652. #endregion
  653. #region Properties
  654. public static TaskFactory Factory {
  655. get {
  656. return defaultFactory;
  657. }
  658. }
  659. public static int? CurrentId {
  660. get {
  661. Task t = current;
  662. return t == null ? (int?)null : t.Id;
  663. }
  664. }
  665. public AggregateException Exception {
  666. get {
  667. exceptionObserved = true;
  668. return exception;
  669. }
  670. internal set {
  671. exception = value;
  672. }
  673. }
  674. public bool IsCanceled {
  675. get {
  676. return status == TaskStatus.Canceled;
  677. }
  678. }
  679. public bool IsCompleted {
  680. get {
  681. return status == TaskStatus.RanToCompletion ||
  682. status == TaskStatus.Canceled || status == TaskStatus.Faulted;
  683. }
  684. }
  685. public bool IsFaulted {
  686. get {
  687. return status == TaskStatus.Faulted;
  688. }
  689. }
  690. public TaskCreationOptions CreationOptions {
  691. get {
  692. return taskCreationOptions;
  693. }
  694. }
  695. public TaskStatus Status {
  696. get {
  697. return status;
  698. }
  699. internal set {
  700. status = value;
  701. }
  702. }
  703. public object AsyncState {
  704. get {
  705. return state;
  706. }
  707. }
  708. bool IAsyncResult.CompletedSynchronously {
  709. get {
  710. return true;
  711. }
  712. }
  713. WaitHandle IAsyncResult.AsyncWaitHandle {
  714. get {
  715. return null;
  716. }
  717. }
  718. public int Id {
  719. get {
  720. return taskId;
  721. }
  722. }
  723. internal Task Parent {
  724. get {
  725. return parent;
  726. }
  727. }
  728. string DisplayActionMethod {
  729. get {
  730. Delegate d = simpleAction ?? (Delegate) action;
  731. return d == null ? "<none>" : d.Method.ToString ();
  732. }
  733. }
  734. #endregion
  735. }
  736. }
  737. #endif