Task.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849
  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 = new ConcurrentQueue<EventHandler> ();
  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. completed.Enqueue (action);
  245. // Retry in case completion was achieved but event adding was too late
  246. if (IsCompleted)
  247. action (null, EventArgs.Empty);
  248. }
  249. bool ContinuationStatusCheck (TaskContinuationOptions kind)
  250. {
  251. if (kind == TaskContinuationOptions.None)
  252. return true;
  253. int kindCode = (int)kind;
  254. if (kindCode >= ((int)TaskContinuationOptions.NotOnRanToCompletion)) {
  255. if (status == TaskStatus.Canceled) {
  256. if (kind == TaskContinuationOptions.NotOnCanceled)
  257. return false;
  258. if (kind == TaskContinuationOptions.OnlyOnFaulted)
  259. return false;
  260. if (kind == TaskContinuationOptions.OnlyOnRanToCompletion)
  261. return false;
  262. } else if (status == TaskStatus.Faulted) {
  263. if (kind == TaskContinuationOptions.NotOnFaulted)
  264. return false;
  265. if (kind == TaskContinuationOptions.OnlyOnCanceled)
  266. return false;
  267. if (kind == TaskContinuationOptions.OnlyOnRanToCompletion)
  268. return false;
  269. } else if (status == TaskStatus.RanToCompletion) {
  270. if (kind == TaskContinuationOptions.NotOnRanToCompletion)
  271. return false;
  272. if (kind == TaskContinuationOptions.OnlyOnFaulted)
  273. return false;
  274. if (kind == TaskContinuationOptions.OnlyOnCanceled)
  275. return false;
  276. }
  277. }
  278. return true;
  279. }
  280. void CheckAndSchedule (Task continuation, TaskContinuationOptions options, TaskScheduler scheduler, bool fromCaller)
  281. {
  282. if ((options & TaskContinuationOptions.ExecuteSynchronously) > 0)
  283. continuation.ThreadStart ();
  284. else
  285. continuation.Start (scheduler);
  286. }
  287. internal TaskCreationOptions GetCreationOptions (TaskContinuationOptions kind)
  288. {
  289. TaskCreationOptions options = TaskCreationOptions.None;
  290. if ((kind & TaskContinuationOptions.AttachedToParent) > 0)
  291. options |= TaskCreationOptions.AttachedToParent;
  292. if ((kind & TaskContinuationOptions.PreferFairness) > 0)
  293. options |= TaskCreationOptions.PreferFairness;
  294. if ((kind & TaskContinuationOptions.LongRunning) > 0)
  295. options |= TaskCreationOptions.LongRunning;
  296. return options;
  297. }
  298. #endregion
  299. #region Internal and protected thingies
  300. internal void Schedule ()
  301. {
  302. status = TaskStatus.WaitingToRun;
  303. // If worker is null it means it is a local one, revert to the old behavior
  304. if (childWorkAdder == null || CheckTaskOptions (taskCreationOptions, TaskCreationOptions.PreferFairness)) {
  305. scheduler.AddWork (this);
  306. } else {
  307. /* Like the semantic of the ABP paper describe it, we add ourselves to the bottom
  308. * of our Parent Task's ThreadWorker deque. It's ok to do that since we are in
  309. * the correct Thread during the creation
  310. */
  311. childWorkAdder (this);
  312. }
  313. }
  314. void ThreadStart ()
  315. {
  316. /* Allow scheduler to break fairness of deque ordering without
  317. * breaking its semantic (the task can be executed twice but the
  318. * second time it will return immediately
  319. */
  320. if (!executing.TryRelaxedSet ())
  321. return;
  322. current = this;
  323. TaskScheduler.Current = taskScheduler;
  324. if (!token.IsCancellationRequested) {
  325. status = TaskStatus.Running;
  326. try {
  327. InnerInvoke ();
  328. } catch (OperationCanceledException oce) {
  329. if (oce.CancellationToken == token)
  330. CancelReal ();
  331. else
  332. HandleGenericException (oce);
  333. } catch (Exception e) {
  334. HandleGenericException (e);
  335. }
  336. } else {
  337. CancelReal ();
  338. }
  339. Finish ();
  340. }
  341. internal void Execute (Action<Task> childAdder)
  342. {
  343. childWorkAdder = childAdder;
  344. ThreadStart ();
  345. }
  346. internal void AddChild ()
  347. {
  348. childTasks.AddCount ();
  349. }
  350. internal void ChildCompleted ()
  351. {
  352. if (childTasks.Signal () && status == TaskStatus.WaitingForChildrenToComplete) {
  353. status = TaskStatus.RanToCompletion;
  354. ProcessCompleteDelegates ();
  355. }
  356. }
  357. internal virtual void InnerInvoke ()
  358. {
  359. if (action != null)
  360. action (state);
  361. // Set action to null so that the GC can collect the delegate and thus
  362. // any big object references that the user might have captured in an anonymous method
  363. action = null;
  364. state = null;
  365. }
  366. internal void Finish ()
  367. {
  368. // If there wasn't any child created in the task we set the CountdownEvent
  369. childTasks.Signal ();
  370. // Don't override Canceled or Faulted
  371. if (status == TaskStatus.Running) {
  372. if (childTasks.IsSet)
  373. status = TaskStatus.RanToCompletion;
  374. else
  375. status = TaskStatus.WaitingForChildrenToComplete;
  376. }
  377. if (status != TaskStatus.WaitingForChildrenToComplete)
  378. ProcessCompleteDelegates ();
  379. // Reset the current thingies
  380. current = null;
  381. TaskScheduler.Current = null;
  382. // Tell parent that we are finished
  383. if (CheckTaskOptions (taskCreationOptions, TaskCreationOptions.AttachedToParent) && parent != null){
  384. parent.ChildCompleted ();
  385. }
  386. }
  387. void ProcessCompleteDelegates ()
  388. {
  389. EventHandler handler;
  390. while (completed.TryDequeue (out handler))
  391. handler (this, EventArgs.Empty);
  392. }
  393. #endregion
  394. #region Cancel and Wait related method
  395. internal void CancelReal ()
  396. {
  397. status = TaskStatus.Canceled;
  398. }
  399. internal void HandleGenericException (Exception e)
  400. {
  401. HandleGenericException (new AggregateException (e));
  402. }
  403. internal void HandleGenericException (AggregateException e)
  404. {
  405. exception = e;
  406. status = TaskStatus.Faulted;
  407. if (taskScheduler != null && taskScheduler.FireUnobservedEvent (exception).Observed)
  408. exceptionObserved = true;
  409. }
  410. public void Wait ()
  411. {
  412. if (scheduler == null)
  413. schedWait.Wait ();
  414. if (!IsCompleted)
  415. scheduler.ParticipateUntil (this);
  416. if (exception != null)
  417. throw exception;
  418. if (IsCanceled)
  419. throw new AggregateException (new TaskCanceledException (this));
  420. }
  421. public void Wait (CancellationToken cancellationToken)
  422. {
  423. Wait (-1, cancellationToken);
  424. }
  425. public bool Wait (TimeSpan timeout)
  426. {
  427. return Wait (CheckTimeout (timeout), CancellationToken.None);
  428. }
  429. public bool Wait (int millisecondsTimeout)
  430. {
  431. return Wait (millisecondsTimeout, CancellationToken.None);
  432. }
  433. public bool Wait (int millisecondsTimeout, CancellationToken cancellationToken)
  434. {
  435. if (millisecondsTimeout < -1)
  436. throw new ArgumentOutOfRangeException ("millisecondsTimeout");
  437. if (millisecondsTimeout == -1 && token == CancellationToken.None) {
  438. Wait ();
  439. return true;
  440. }
  441. Watch watch = Watch.StartNew ();
  442. if (scheduler == null) {
  443. schedWait.Wait (millisecondsTimeout, cancellationToken);
  444. millisecondsTimeout = ComputeTimeout (millisecondsTimeout, watch);
  445. }
  446. ManualResetEventSlim predicateEvt = new ManualResetEventSlim (false);
  447. if (cancellationToken != CancellationToken.None) {
  448. cancellationToken.Register (predicateEvt.Set);
  449. cancellationToken.ThrowIfCancellationRequested ();
  450. }
  451. bool result = scheduler.ParticipateUntil (this, predicateEvt, millisecondsTimeout);
  452. if (exception != null)
  453. throw exception;
  454. if (IsCanceled)
  455. throw new AggregateException (new TaskCanceledException (this));
  456. return !result;
  457. }
  458. public static void WaitAll (params Task[] tasks)
  459. {
  460. if (tasks == null)
  461. throw new ArgumentNullException ("tasks");
  462. if (tasks.Length == 0)
  463. throw new ArgumentException ("tasks is empty", "tasks");
  464. foreach (var t in tasks)
  465. t.Wait ();
  466. }
  467. public static void WaitAll (Task[] tasks, CancellationToken cancellationToken)
  468. {
  469. if (tasks == null)
  470. throw new ArgumentNullException ("tasks");
  471. if (tasks.Length == 0)
  472. throw new ArgumentException ("tasks is empty", "tasks");
  473. foreach (var t in tasks)
  474. t.Wait (cancellationToken);
  475. }
  476. public static bool WaitAll (Task[] tasks, TimeSpan timeout)
  477. {
  478. if (tasks == null)
  479. throw new ArgumentNullException ("tasks");
  480. if (tasks.Length == 0)
  481. throw new ArgumentException ("tasks is empty", "tasks");
  482. bool result = true;
  483. foreach (var t in tasks)
  484. result &= t.Wait (timeout);
  485. return result;
  486. }
  487. public static bool WaitAll (Task[] tasks, int millisecondsTimeout)
  488. {
  489. if (tasks == null)
  490. throw new ArgumentNullException ("tasks");
  491. if (tasks.Length == 0)
  492. throw new ArgumentException ("tasks is empty", "tasks");
  493. bool result = true;
  494. foreach (var t in tasks)
  495. result &= t.Wait (millisecondsTimeout);
  496. return result;
  497. }
  498. public static bool WaitAll (Task[] tasks, int millisecondsTimeout, CancellationToken cancellationToken)
  499. {
  500. if (tasks == null)
  501. throw new ArgumentNullException ("tasks");
  502. if (tasks.Length == 0)
  503. throw new ArgumentException ("tasks is empty", "tasks");
  504. bool result = true;
  505. foreach (var t in tasks)
  506. result &= t.Wait (millisecondsTimeout, cancellationToken);
  507. return result;
  508. }
  509. public static int WaitAny (params Task[] tasks)
  510. {
  511. return WaitAny (tasks, -1, CancellationToken.None);
  512. }
  513. public static int WaitAny (Task[] tasks, TimeSpan timeout)
  514. {
  515. return WaitAny (tasks, CheckTimeout (timeout));
  516. }
  517. public static int WaitAny (Task[] tasks, int millisecondsTimeout)
  518. {
  519. if (millisecondsTimeout < -1)
  520. throw new ArgumentOutOfRangeException ("millisecondsTimeout");
  521. if (millisecondsTimeout == -1)
  522. return WaitAny (tasks);
  523. return WaitAny (tasks, millisecondsTimeout, CancellationToken.None);
  524. }
  525. public static int WaitAny (Task[] tasks, CancellationToken cancellationToken)
  526. {
  527. return WaitAny (tasks, -1, cancellationToken);
  528. }
  529. public static int WaitAny (Task[] tasks, int millisecondsTimeout, CancellationToken cancellationToken)
  530. {
  531. if (tasks == null)
  532. throw new ArgumentNullException ("tasks");
  533. if (tasks.Length == 0)
  534. throw new ArgumentException ("tasks is empty", "tasks");
  535. if (tasks.Length == 1) {
  536. tasks[0].Wait (millisecondsTimeout, cancellationToken);
  537. return 0;
  538. }
  539. int numFinished = 0;
  540. int indexFirstFinished = -1;
  541. int index = 0;
  542. IScheduler sched = null;
  543. Task task = null;
  544. Watch watch = Watch.StartNew ();
  545. ManualResetEventSlim predicateEvt = new ManualResetEventSlim (false);
  546. foreach (Task t in tasks) {
  547. int indexResult = index++;
  548. t.ContinueWith (delegate {
  549. if (numFinished >= 1)
  550. return;
  551. int result = Interlocked.Increment (ref numFinished);
  552. // Check if we are the first to have finished
  553. if (result == 1)
  554. indexFirstFinished = indexResult;
  555. // Stop waiting
  556. predicateEvt.Set ();
  557. }, TaskContinuationOptions.ExecuteSynchronously);
  558. if (sched == null && t.scheduler != null) {
  559. task = t;
  560. sched = t.scheduler;
  561. }
  562. }
  563. // If none of task have a scheduler we are forced to wait for at least one to start
  564. if (sched == null) {
  565. var handles = Array.ConvertAll (tasks, t => t.schedWait.WaitHandle);
  566. int shandle = -1;
  567. if ((shandle = WaitHandle.WaitAny (handles, millisecondsTimeout)) == WaitHandle.WaitTimeout)
  568. return -1;
  569. sched = tasks[shandle].scheduler;
  570. task = tasks[shandle];
  571. millisecondsTimeout = ComputeTimeout (millisecondsTimeout, watch);
  572. }
  573. // One task already finished
  574. if (indexFirstFinished != -1)
  575. return indexFirstFinished;
  576. if (cancellationToken != CancellationToken.None) {
  577. cancellationToken.Register (predicateEvt.Set);
  578. cancellationToken.ThrowIfCancellationRequested ();
  579. }
  580. sched.ParticipateUntil (task, predicateEvt, millisecondsTimeout);
  581. // Index update is still not done
  582. if (indexFirstFinished == -1) {
  583. SpinWait wait = new SpinWait ();
  584. while (indexFirstFinished == -1)
  585. wait.SpinOnce ();
  586. }
  587. return indexFirstFinished;
  588. }
  589. static int CheckTimeout (TimeSpan timeout)
  590. {
  591. try {
  592. return checked ((int)timeout.TotalMilliseconds);
  593. } catch (System.OverflowException) {
  594. throw new ArgumentOutOfRangeException ("timeout");
  595. }
  596. }
  597. static int ComputeTimeout (int millisecondsTimeout, Watch watch)
  598. {
  599. return millisecondsTimeout == -1 ? -1 : (int)Math.Max (watch.ElapsedMilliseconds - millisecondsTimeout, 1);
  600. }
  601. #endregion
  602. #region Dispose
  603. public void Dispose ()
  604. {
  605. Dispose (true);
  606. }
  607. protected virtual void Dispose (bool disposing)
  608. {
  609. // Set action to null so that the GC can collect the delegate and thus
  610. // any big object references that the user might have captured in a anonymous method
  611. if (disposing) {
  612. action = null;
  613. state = null;
  614. }
  615. }
  616. #endregion
  617. #region Properties
  618. public static TaskFactory Factory {
  619. get {
  620. return defaultFactory;
  621. }
  622. }
  623. public static int? CurrentId {
  624. get {
  625. Task t = current;
  626. return t == null ? (int?)null : t.Id;
  627. }
  628. }
  629. public AggregateException Exception {
  630. get {
  631. exceptionObserved = true;
  632. return exception;
  633. }
  634. internal set {
  635. exception = value;
  636. }
  637. }
  638. public bool IsCanceled {
  639. get {
  640. return status == TaskStatus.Canceled;
  641. }
  642. }
  643. public bool IsCompleted {
  644. get {
  645. return status == TaskStatus.RanToCompletion ||
  646. status == TaskStatus.Canceled || status == TaskStatus.Faulted;
  647. }
  648. }
  649. public bool IsFaulted {
  650. get {
  651. return status == TaskStatus.Faulted;
  652. }
  653. }
  654. public TaskCreationOptions CreationOptions {
  655. get {
  656. return taskCreationOptions;
  657. }
  658. }
  659. public TaskStatus Status {
  660. get {
  661. return status;
  662. }
  663. internal set {
  664. status = value;
  665. }
  666. }
  667. public object AsyncState {
  668. get {
  669. return state;
  670. }
  671. }
  672. bool IAsyncResult.CompletedSynchronously {
  673. get {
  674. return true;
  675. }
  676. }
  677. WaitHandle IAsyncResult.AsyncWaitHandle {
  678. get {
  679. return null;
  680. }
  681. }
  682. public int Id {
  683. get {
  684. return taskId;
  685. }
  686. }
  687. internal Task Parent {
  688. get {
  689. return parent;
  690. }
  691. }
  692. #endregion
  693. }
  694. }
  695. #endif