Task.cs 23 KB

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