Task.cs 23 KB

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