Task.cs 22 KB

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