Task.cs 26 KB

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