2
0

Task.cs 22 KB

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