Task.cs 25 KB

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