Task.cs 23 KB

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