Task.cs 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063
  1. //
  2. // Task.cs
  3. //
  4. // Authors:
  5. // Marek Safar <[email protected]>
  6. //
  7. // Copyright (c) 2008 Jérémie "Garuma" Laval
  8. // Copyright 2011 Xamarin Inc (http://www.xamarin.com).
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining a copy
  11. // of this software and associated documentation files (the "Software"), to deal
  12. // in the Software without restriction, including without limitation the rights
  13. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  14. // copies of the Software, and to permit persons to whom the Software is
  15. // furnished to do so, subject to the following conditions:
  16. //
  17. // The above copyright notice and this permission notice shall be included in
  18. // all copies or substantial portions of the Software.
  19. //
  20. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  21. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  22. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  23. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  24. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  25. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  26. // THE SOFTWARE.
  27. //
  28. //
  29. #if NET_4_0 || MOBILE
  30. using System;
  31. using System.Threading;
  32. using System.Collections.Concurrent;
  33. using System.Collections.Generic;
  34. using System.Runtime.CompilerServices;
  35. namespace System.Threading.Tasks
  36. {
  37. [System.Diagnostics.DebuggerDisplay ("Id = {Id}, Status = {Status}")]
  38. [System.Diagnostics.DebuggerTypeProxy (typeof (TaskDebuggerView))]
  39. public class Task : IDisposable, IAsyncResult
  40. {
  41. // With this attribute each thread has its own value so that it's correct for our Schedule code
  42. // and for Parent property.
  43. [System.ThreadStatic]
  44. static Task current;
  45. [System.ThreadStatic]
  46. static Action<Task> childWorkAdder;
  47. Task parent;
  48. static int id = -1;
  49. static readonly TaskFactory defaultFactory = new TaskFactory ();
  50. static readonly Watch watch = Watch.StartNew ();
  51. CountdownEvent childTasks;
  52. int taskId;
  53. TaskCreationOptions taskCreationOptions;
  54. TaskScheduler scheduler;
  55. volatile AggregateException exception;
  56. volatile bool exceptionObserved;
  57. ConcurrentQueue<AggregateException> childExceptions;
  58. TaskStatus status;
  59. Action<object> action;
  60. Action simpleAction;
  61. object state;
  62. AtomicBooleanValue executing;
  63. TaskCompletionQueue<Task> completed;
  64. TaskCompletionQueue<ManualResetEventSlim> registeredEvts;
  65. // If this task is a continuation, this stuff gets filled
  66. CompletionSlot Slot;
  67. CancellationToken token;
  68. CancellationTokenRegistration? cancellationRegistration;
  69. internal const TaskCreationOptions WorkerTaskNotSupportedOptions = TaskCreationOptions.LongRunning | TaskCreationOptions.PreferFairness;
  70. const TaskCreationOptions MaxTaskCreationOptions =
  71. #if NET_4_5
  72. TaskCreationOptions.DenyChildAttach | TaskCreationOptions.HideScheduler |
  73. #endif
  74. TaskCreationOptions.PreferFairness | TaskCreationOptions.LongRunning | TaskCreationOptions.AttachedToParent;
  75. public Task (Action action) : this (action, TaskCreationOptions.None)
  76. {
  77. }
  78. public Task (Action action, TaskCreationOptions creationOptions) : this (action, CancellationToken.None, creationOptions)
  79. {
  80. }
  81. public Task (Action action, CancellationToken cancellationToken) : this (action, cancellationToken, TaskCreationOptions.None)
  82. {
  83. }
  84. public Task (Action action, CancellationToken cancellationToken, TaskCreationOptions creationOptions)
  85. : this (null, null, cancellationToken, creationOptions, current)
  86. {
  87. if (action == null)
  88. throw new ArgumentNullException ("action");
  89. if (creationOptions > MaxTaskCreationOptions || creationOptions < TaskCreationOptions.None)
  90. throw new ArgumentOutOfRangeException ("creationOptions");
  91. this.simpleAction = action;
  92. }
  93. public Task (Action<object> action, object state) : this (action, state, TaskCreationOptions.None)
  94. {
  95. }
  96. public Task (Action<object> action, object state, TaskCreationOptions creationOptions)
  97. : this (action, state, CancellationToken.None, creationOptions)
  98. {
  99. }
  100. public Task (Action<object> action, object state, CancellationToken cancellationToken)
  101. : this (action, state, cancellationToken, TaskCreationOptions.None)
  102. {
  103. }
  104. public Task (Action<object> action, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions)
  105. : this (action, state, cancellationToken, creationOptions, current)
  106. {
  107. if (action == null)
  108. throw new ArgumentNullException ("action");
  109. if (creationOptions > MaxTaskCreationOptions || creationOptions < TaskCreationOptions.None)
  110. throw new ArgumentOutOfRangeException ("creationOptions");
  111. }
  112. internal Task (Action<object> action,
  113. object state,
  114. CancellationToken cancellationToken,
  115. TaskCreationOptions creationOptions,
  116. Task parent)
  117. {
  118. this.taskCreationOptions = creationOptions;
  119. this.action = action;
  120. this.state = state;
  121. this.taskId = Interlocked.Increment (ref id);
  122. this.status = cancellationToken.IsCancellationRequested ? TaskStatus.Canceled : TaskStatus.Created;
  123. this.token = cancellationToken;
  124. this.parent = parent;
  125. // Process taskCreationOptions
  126. if (CheckTaskOptions (taskCreationOptions, TaskCreationOptions.AttachedToParent) && parent != null)
  127. parent.AddChild ();
  128. if (token.CanBeCanceled)
  129. cancellationRegistration = token.Register (l => ((Task) l).CancelReal (), this);
  130. }
  131. ~Task ()
  132. {
  133. if (exception != null && !exceptionObserved)
  134. throw exception;
  135. }
  136. bool CheckTaskOptions (TaskCreationOptions opt, TaskCreationOptions member)
  137. {
  138. return (opt & member) == member;
  139. }
  140. #region Start
  141. public void Start ()
  142. {
  143. Start (TaskScheduler.Current);
  144. }
  145. public void Start (TaskScheduler scheduler)
  146. {
  147. if (scheduler == null)
  148. throw new ArgumentNullException ("scheduler");
  149. if (status >= TaskStatus.WaitingToRun)
  150. throw new InvalidOperationException ("The Task is not in a valid state to be started.");
  151. if (Slot.Initialized)
  152. throw new InvalidOperationException ("Start may not be called on a continuation task");
  153. SetupScheduler (scheduler);
  154. Schedule ();
  155. }
  156. internal void SetupScheduler (TaskScheduler scheduler)
  157. {
  158. this.scheduler = scheduler;
  159. status = TaskStatus.WaitingForActivation;
  160. }
  161. public void RunSynchronously ()
  162. {
  163. RunSynchronously (TaskScheduler.Current);
  164. }
  165. public void RunSynchronously (TaskScheduler scheduler)
  166. {
  167. if (scheduler == null)
  168. throw new ArgumentNullException ("scheduler");
  169. if (Status > TaskStatus.WaitingForActivation)
  170. throw new InvalidOperationException ("The task is not in a valid state to be started");
  171. SetupScheduler (scheduler);
  172. var saveStatus = status;
  173. status = TaskStatus.WaitingToRun;
  174. try {
  175. if (scheduler.RunInline (this))
  176. return;
  177. } catch (Exception inner) {
  178. throw new TaskSchedulerException (inner);
  179. }
  180. status = saveStatus;
  181. Start (scheduler);
  182. Wait ();
  183. }
  184. #endregion
  185. #region ContinueWith
  186. public Task ContinueWith (Action<Task> continuationAction)
  187. {
  188. return ContinueWith (continuationAction, TaskContinuationOptions.None);
  189. }
  190. public Task ContinueWith (Action<Task> continuationAction, TaskContinuationOptions continuationOptions)
  191. {
  192. return ContinueWith (continuationAction, CancellationToken.None, continuationOptions, TaskScheduler.Current);
  193. }
  194. public Task ContinueWith (Action<Task> continuationAction, CancellationToken cancellationToken)
  195. {
  196. return ContinueWith (continuationAction, cancellationToken, TaskContinuationOptions.None, TaskScheduler.Current);
  197. }
  198. public Task ContinueWith (Action<Task> continuationAction, TaskScheduler scheduler)
  199. {
  200. return ContinueWith (continuationAction, CancellationToken.None, TaskContinuationOptions.None, scheduler);
  201. }
  202. public Task ContinueWith (Action<Task> continuationAction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
  203. {
  204. if (continuationAction == null)
  205. throw new ArgumentNullException ("continuationAction");
  206. if (scheduler == null)
  207. throw new ArgumentNullException ("scheduler");
  208. Task continuation = new Task (l => continuationAction ((Task)l),
  209. this,
  210. cancellationToken,
  211. GetCreationOptions (continuationOptions),
  212. this);
  213. ContinueWithCore (continuation, continuationOptions, scheduler);
  214. return continuation;
  215. }
  216. public Task<TResult> ContinueWith<TResult> (Func<Task, TResult> continuationFunction)
  217. {
  218. return ContinueWith<TResult> (continuationFunction, TaskContinuationOptions.None);
  219. }
  220. public Task<TResult> ContinueWith<TResult> (Func<Task, TResult> continuationFunction, TaskContinuationOptions continuationOptions)
  221. {
  222. return ContinueWith<TResult> (continuationFunction, CancellationToken.None, continuationOptions, TaskScheduler.Current);
  223. }
  224. public Task<TResult> ContinueWith<TResult> (Func<Task, TResult> continuationFunction, CancellationToken cancellationToken)
  225. {
  226. return ContinueWith<TResult> (continuationFunction, cancellationToken, TaskContinuationOptions.None, TaskScheduler.Current);
  227. }
  228. public Task<TResult> ContinueWith<TResult> (Func<Task, TResult> continuationFunction, TaskScheduler scheduler)
  229. {
  230. return ContinueWith<TResult> (continuationFunction, CancellationToken.None, TaskContinuationOptions.None, scheduler);
  231. }
  232. public Task<TResult> ContinueWith<TResult> (Func<Task, TResult> continuationFunction, CancellationToken cancellationToken,
  233. TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
  234. {
  235. if (continuationFunction == null)
  236. throw new ArgumentNullException ("continuationFunction");
  237. if (scheduler == null)
  238. throw new ArgumentNullException ("scheduler");
  239. Task<TResult> t = new Task<TResult> ((o) => continuationFunction ((Task)o),
  240. this,
  241. cancellationToken,
  242. GetCreationOptions (continuationOptions),
  243. this);
  244. ContinueWithCore (t, continuationOptions, scheduler);
  245. return t;
  246. }
  247. internal void ContinueWithCore (Task continuation, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
  248. {
  249. ContinueWithCore (continuation, continuationOptions, scheduler, null);
  250. }
  251. internal void ContinueWithCore (Task continuation, TaskContinuationOptions kind,
  252. TaskScheduler scheduler, Func<bool> predicate)
  253. {
  254. // Already set the scheduler so that user can call Wait and that sort of stuff
  255. continuation.scheduler = scheduler;
  256. continuation.status = TaskStatus.WaitingForActivation;
  257. continuation.Slot = new CompletionSlot (kind, predicate);
  258. if (IsCompleted) {
  259. CompletionExecutor (continuation);
  260. return;
  261. }
  262. completed.Add (continuation);
  263. // Retry in case completion was achieved but event adding was too late
  264. if (IsCompleted)
  265. CompletionExecutor (continuation);
  266. }
  267. bool ContinuationStatusCheck (TaskContinuationOptions kind)
  268. {
  269. if (kind == TaskContinuationOptions.None)
  270. return true;
  271. int kindCode = (int)kind;
  272. if (kindCode >= ((int)TaskContinuationOptions.NotOnRanToCompletion)) {
  273. // Remove other options
  274. kind &= ~(TaskContinuationOptions.PreferFairness
  275. | TaskContinuationOptions.LongRunning
  276. | TaskContinuationOptions.AttachedToParent
  277. | TaskContinuationOptions.ExecuteSynchronously);
  278. if (status == TaskStatus.Canceled) {
  279. if (kind == TaskContinuationOptions.NotOnCanceled)
  280. return false;
  281. if (kind == TaskContinuationOptions.OnlyOnFaulted)
  282. return false;
  283. if (kind == TaskContinuationOptions.OnlyOnRanToCompletion)
  284. return false;
  285. } else if (status == TaskStatus.Faulted) {
  286. if (kind == TaskContinuationOptions.NotOnFaulted)
  287. return false;
  288. if (kind == TaskContinuationOptions.OnlyOnCanceled)
  289. return false;
  290. if (kind == TaskContinuationOptions.OnlyOnRanToCompletion)
  291. return false;
  292. } else if (status == TaskStatus.RanToCompletion) {
  293. if (kind == TaskContinuationOptions.NotOnRanToCompletion)
  294. return false;
  295. if (kind == TaskContinuationOptions.OnlyOnFaulted)
  296. return false;
  297. if (kind == TaskContinuationOptions.OnlyOnCanceled)
  298. return false;
  299. }
  300. }
  301. return true;
  302. }
  303. static internal TaskCreationOptions GetCreationOptions (TaskContinuationOptions kind)
  304. {
  305. TaskCreationOptions options = TaskCreationOptions.None;
  306. if ((kind & TaskContinuationOptions.AttachedToParent) > 0)
  307. options |= TaskCreationOptions.AttachedToParent;
  308. if ((kind & TaskContinuationOptions.PreferFairness) > 0)
  309. options |= TaskCreationOptions.PreferFairness;
  310. if ((kind & TaskContinuationOptions.LongRunning) > 0)
  311. options |= TaskCreationOptions.LongRunning;
  312. return options;
  313. }
  314. internal void RegisterWaitEvent (ManualResetEventSlim evt)
  315. {
  316. if (IsCompleted) {
  317. evt.Set ();
  318. return;
  319. }
  320. registeredEvts.Add (evt);
  321. if (IsCompleted)
  322. evt.Set ();
  323. }
  324. #endregion
  325. #region Internal and protected thingies
  326. internal void Schedule ()
  327. {
  328. status = TaskStatus.WaitingToRun;
  329. // If worker is null it means it is a local one, revert to the old behavior
  330. // If TaskScheduler.Current is not being used, the scheduler was explicitly provided, so we must use that
  331. if (scheduler != TaskScheduler.Current || childWorkAdder == null || CheckTaskOptions (taskCreationOptions, TaskCreationOptions.PreferFairness)) {
  332. scheduler.QueueTask (this);
  333. } else {
  334. /* Like the semantic of the ABP paper describe it, we add ourselves to the bottom
  335. * of our Parent Task's ThreadWorker deque. It's ok to do that since we are in
  336. * the correct Thread during the creation
  337. */
  338. childWorkAdder (this);
  339. }
  340. }
  341. void ThreadStart ()
  342. {
  343. /* Allow scheduler to break fairness of deque ordering without
  344. * breaking its semantic (the task can be executed twice but the
  345. * second time it will return immediately
  346. */
  347. if (!executing.TryRelaxedSet ())
  348. return;
  349. // Disable CancellationToken direct cancellation
  350. if (cancellationRegistration != null) {
  351. cancellationRegistration.Value.Dispose ();
  352. cancellationRegistration = null;
  353. }
  354. current = this;
  355. TaskScheduler.Current = scheduler;
  356. if (!token.IsCancellationRequested) {
  357. status = TaskStatus.Running;
  358. try {
  359. InnerInvoke ();
  360. } catch (OperationCanceledException oce) {
  361. if (token != CancellationToken.None && oce.CancellationToken == token)
  362. CancelReal ();
  363. else
  364. HandleGenericException (oce);
  365. } catch (Exception e) {
  366. HandleGenericException (e);
  367. }
  368. } else {
  369. CancelReal ();
  370. }
  371. Finish ();
  372. }
  373. internal void Execute (Action<Task> childAdder)
  374. {
  375. childWorkAdder = childAdder;
  376. ThreadStart ();
  377. }
  378. internal void AddChild ()
  379. {
  380. if (childTasks == null)
  381. Interlocked.CompareExchange (ref childTasks, new CountdownEvent (1), null);
  382. childTasks.AddCount ();
  383. }
  384. internal void ChildCompleted (AggregateException childEx)
  385. {
  386. if (childEx != null) {
  387. if (childExceptions == null)
  388. Interlocked.CompareExchange (ref childExceptions, new ConcurrentQueue<AggregateException> (), null);
  389. childExceptions.Enqueue (childEx);
  390. }
  391. if (childTasks.Signal () && status == TaskStatus.WaitingForChildrenToComplete) {
  392. status = TaskStatus.RanToCompletion;
  393. ProcessChildExceptions ();
  394. ProcessCompleteDelegates ();
  395. }
  396. }
  397. internal virtual void InnerInvoke ()
  398. {
  399. if (action == null && simpleAction != null)
  400. simpleAction ();
  401. else if (action != null)
  402. action (state);
  403. // Set action to null so that the GC can collect the delegate and thus
  404. // any big object references that the user might have captured in an anonymous method
  405. action = null;
  406. simpleAction = null;
  407. state = null;
  408. }
  409. internal void Finish ()
  410. {
  411. // If there was children created and they all finished, we set the countdown
  412. if (childTasks != null)
  413. childTasks.Signal ();
  414. // Don't override Canceled or Faulted
  415. if (status == TaskStatus.Running) {
  416. if (childTasks == null || childTasks.IsSet)
  417. status = TaskStatus.RanToCompletion;
  418. else
  419. status = TaskStatus.WaitingForChildrenToComplete;
  420. }
  421. if (status != TaskStatus.WaitingForChildrenToComplete)
  422. ProcessCompleteDelegates ();
  423. // Reset the current thingies
  424. current = null;
  425. TaskScheduler.Current = null;
  426. if (cancellationRegistration.HasValue)
  427. cancellationRegistration.Value.Dispose ();
  428. // Tell parent that we are finished
  429. if (CheckTaskOptions (taskCreationOptions, TaskCreationOptions.AttachedToParent) && parent != null) {
  430. parent.ChildCompleted (this.Exception);
  431. }
  432. }
  433. void CompletionExecutor (Task cont)
  434. {
  435. if (cont.Slot.Predicate != null && !cont.Slot.Predicate ())
  436. return;
  437. if (!cont.Slot.Launched.TryRelaxedSet ())
  438. return;
  439. if (!ContinuationStatusCheck (cont.Slot.Kind)) {
  440. cont.CancelReal ();
  441. cont.Dispose ();
  442. return;
  443. }
  444. if ((cont.Slot.Kind & TaskContinuationOptions.ExecuteSynchronously) != 0)
  445. cont.RunSynchronously (cont.scheduler);
  446. else
  447. cont.Schedule ();
  448. }
  449. void ProcessCompleteDelegates ()
  450. {
  451. if (completed.HasElements) {
  452. Task continuation;
  453. while (completed.TryGetNextCompletion (out continuation))
  454. CompletionExecutor (continuation);
  455. }
  456. if (registeredEvts.HasElements) {
  457. ManualResetEventSlim evt;
  458. while (registeredEvts.TryGetNextCompletion (out evt))
  459. evt.Set ();
  460. }
  461. }
  462. void ProcessChildExceptions ()
  463. {
  464. if (childExceptions == null)
  465. return;
  466. if (exception == null)
  467. exception = new AggregateException ();
  468. AggregateException childEx;
  469. while (childExceptions.TryDequeue (out childEx))
  470. exception.AddChildException (childEx);
  471. }
  472. #endregion
  473. #region Cancel and Wait related method
  474. internal void CancelReal ()
  475. {
  476. status = TaskStatus.Canceled;
  477. ProcessCompleteDelegates ();
  478. }
  479. internal void HandleGenericException (Exception e)
  480. {
  481. HandleGenericException (new AggregateException (e));
  482. }
  483. internal void HandleGenericException (AggregateException e)
  484. {
  485. exception = e;
  486. Thread.MemoryBarrier ();
  487. status = TaskStatus.Faulted;
  488. if (scheduler != null && scheduler.FireUnobservedEvent (exception).Observed)
  489. exceptionObserved = true;
  490. }
  491. public void Wait ()
  492. {
  493. Wait (Timeout.Infinite, CancellationToken.None);
  494. }
  495. public void Wait (CancellationToken cancellationToken)
  496. {
  497. Wait (Timeout.Infinite, cancellationToken);
  498. }
  499. public bool Wait (TimeSpan timeout)
  500. {
  501. return Wait (CheckTimeout (timeout), CancellationToken.None);
  502. }
  503. public bool Wait (int millisecondsTimeout)
  504. {
  505. return Wait (millisecondsTimeout, CancellationToken.None);
  506. }
  507. public bool Wait (int millisecondsTimeout, CancellationToken cancellationToken)
  508. {
  509. if (millisecondsTimeout < -1)
  510. throw new ArgumentOutOfRangeException ("millisecondsTimeout");
  511. bool result = true;
  512. if (!IsCompleted) {
  513. // If the task is ready to be run and we were supposed to wait on it indefinitely, just run it
  514. if (Status == TaskStatus.WaitingToRun && millisecondsTimeout == -1 && scheduler != null)
  515. Execute (null);
  516. if (!IsCompleted) {
  517. // Free heavy ressources used by the event automatically but without removing
  518. // it from the queue since Set () doesn't trigger ObjectDisposedException
  519. using (var evt = new ManualResetEventSlim ()) {
  520. RegisterWaitEvent (evt);
  521. result = evt.Wait (millisecondsTimeout, cancellationToken);
  522. }
  523. }
  524. }
  525. if (IsCanceled)
  526. throw new AggregateException (new TaskCanceledException (this));
  527. if (exception != null)
  528. throw exception;
  529. return result;
  530. }
  531. public static void WaitAll (params Task[] tasks)
  532. {
  533. WaitAll (tasks, Timeout.Infinite, CancellationToken.None);
  534. }
  535. public static void WaitAll (Task[] tasks, CancellationToken cancellationToken)
  536. {
  537. WaitAll (tasks, Timeout.Infinite, cancellationToken);
  538. }
  539. public static bool WaitAll (Task[] tasks, TimeSpan timeout)
  540. {
  541. return WaitAll (tasks, CheckTimeout (timeout), CancellationToken.None);
  542. }
  543. public static bool WaitAll (Task[] tasks, int millisecondsTimeout)
  544. {
  545. return WaitAll (tasks, millisecondsTimeout, CancellationToken.None);
  546. }
  547. public static bool WaitAll (Task[] tasks, int millisecondsTimeout, CancellationToken cancellationToken)
  548. {
  549. if (tasks == null)
  550. throw new ArgumentNullException ("tasks");
  551. CheckForNullTasks (tasks);
  552. bool result = true;
  553. List<Exception> exceptions = null;
  554. long start = watch.ElapsedMilliseconds;
  555. foreach (var t in tasks) {
  556. try {
  557. result &= t.Wait (millisecondsTimeout, cancellationToken);
  558. } catch (AggregateException e) {
  559. if (exceptions == null)
  560. exceptions = new List<Exception> ();
  561. exceptions.AddRange (e.InnerExceptions);
  562. }
  563. if (!ComputeTimeout (ref millisecondsTimeout, start, watch))
  564. result = false;
  565. if (!result)
  566. break;
  567. }
  568. if (exceptions != null)
  569. throw new AggregateException (exceptions);
  570. return result;
  571. }
  572. public static int WaitAny (params Task[] tasks)
  573. {
  574. return WaitAny (tasks, Timeout.Infinite, CancellationToken.None);
  575. }
  576. public static int WaitAny (Task[] tasks, TimeSpan timeout)
  577. {
  578. return WaitAny (tasks, CheckTimeout (timeout));
  579. }
  580. public static int WaitAny (Task[] tasks, int millisecondsTimeout)
  581. {
  582. return WaitAny (tasks, millisecondsTimeout, CancellationToken.None);
  583. }
  584. public static int WaitAny (Task[] tasks, CancellationToken cancellationToken)
  585. {
  586. return WaitAny (tasks, Timeout.Infinite, cancellationToken);
  587. }
  588. public static int WaitAny (Task[] tasks, int millisecondsTimeout, CancellationToken cancellationToken)
  589. {
  590. if (tasks == null)
  591. throw new ArgumentNullException ("tasks");
  592. if (millisecondsTimeout < -1)
  593. throw new ArgumentOutOfRangeException ("millisecondsTimeout");
  594. CheckForNullTasks (tasks);
  595. if (tasks.Length > 0) {
  596. using (var evt = new ManualResetEventSlim ()) {
  597. for (int i = 0; i < tasks.Length; i++) {
  598. var t = tasks[i];
  599. if (t.IsCompleted)
  600. return i;
  601. t.RegisterWaitEvent (evt);
  602. }
  603. if (!evt.Wait (millisecondsTimeout, cancellationToken))
  604. return -1;
  605. }
  606. }
  607. int firstFinished = -1;
  608. for (int i = 0; i < tasks.Length; i++) {
  609. var t = tasks[i];
  610. if (t.IsCompleted) {
  611. firstFinished = i;
  612. break;
  613. }
  614. }
  615. return firstFinished;
  616. }
  617. static int CheckTimeout (TimeSpan timeout)
  618. {
  619. try {
  620. return checked ((int)timeout.TotalMilliseconds);
  621. } catch (System.OverflowException) {
  622. throw new ArgumentOutOfRangeException ("timeout");
  623. }
  624. }
  625. static bool ComputeTimeout (ref int millisecondsTimeout, long start, Watch watch)
  626. {
  627. if (millisecondsTimeout == -1)
  628. return true;
  629. return (millisecondsTimeout = millisecondsTimeout - (int)(watch.ElapsedMilliseconds - start)) >= 1;
  630. }
  631. static void CheckForNullTasks (Task[] tasks)
  632. {
  633. foreach (var t in tasks)
  634. if (t == null)
  635. throw new ArgumentNullException ("tasks", "the tasks argument contains a null element");
  636. }
  637. #endregion
  638. #region Dispose
  639. public void Dispose ()
  640. {
  641. Dispose (true);
  642. }
  643. protected virtual void Dispose (bool disposing)
  644. {
  645. if (!IsCompleted)
  646. throw new InvalidOperationException ("A task may only be disposed if it is in a completion state");
  647. // Set action to null so that the GC can collect the delegate and thus
  648. // any big object references that the user might have captured in a anonymous method
  649. if (disposing) {
  650. action = null;
  651. state = null;
  652. if (cancellationRegistration != null)
  653. cancellationRegistration.Value.Dispose ();
  654. }
  655. }
  656. #endregion
  657. #if NET_4_5
  658. public ConfiguredTaskAwaitable ConfigureAwait (bool continueOnCapturedContext)
  659. {
  660. return new ConfiguredTaskAwaitable (this, continueOnCapturedContext);
  661. }
  662. public Task ContinueWith (Action<Task, object> continuationAction, object state)
  663. {
  664. return ContinueWith (continuationAction, state, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Current);
  665. }
  666. public Task ContinueWith (Action<Task, object> continuationAction, object state, CancellationToken cancellationToken)
  667. {
  668. return ContinueWith (continuationAction, state, cancellationToken, TaskContinuationOptions.None, TaskScheduler.Current);
  669. }
  670. public Task ContinueWith (Action<Task, object> continuationAction, object state, TaskContinuationOptions continuationOptions)
  671. {
  672. return ContinueWith (continuationAction, state, CancellationToken.None, continuationOptions, TaskScheduler.Current);
  673. }
  674. public Task ContinueWith (Action<Task, object> continuationAction, object state, TaskScheduler scheduler)
  675. {
  676. return ContinueWith (continuationAction, state, CancellationToken.None, TaskContinuationOptions.None, scheduler);
  677. }
  678. public Task ContinueWith (Action<Task, object> continuationAction, object state, CancellationToken cancellationToken,
  679. TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
  680. {
  681. if (continuationAction == null)
  682. throw new ArgumentNullException ("continuationAction");
  683. if (scheduler == null)
  684. throw new ArgumentNullException ("scheduler");
  685. Task continuation = new Task (l => continuationAction (this, l), state,
  686. cancellationToken,
  687. GetCreationOptions (continuationOptions),
  688. this);
  689. ContinueWithCore (continuation, continuationOptions, scheduler);
  690. return continuation;
  691. }
  692. public Task<TResult> ContinueWith<TResult> (Func<Task, object, TResult> continuationFunction, object state)
  693. {
  694. return ContinueWith<TResult> (continuationFunction, state, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Current);
  695. }
  696. public Task<TResult> ContinueWith<TResult> (Func<Task, object, TResult> continuationFunction, object state, TaskContinuationOptions continuationOptions)
  697. {
  698. return ContinueWith<TResult> (continuationFunction, state, CancellationToken.None, continuationOptions, TaskScheduler.Current);
  699. }
  700. public Task<TResult> ContinueWith<TResult> (Func<Task, object, TResult> continuationFunction, object state, CancellationToken cancellationToken)
  701. {
  702. return ContinueWith<TResult> (continuationFunction, state, cancellationToken, TaskContinuationOptions.None, TaskScheduler.Current);
  703. }
  704. public Task<TResult> ContinueWith<TResult> (Func<Task, object, TResult> continuationFunction, object state, TaskScheduler scheduler)
  705. {
  706. return ContinueWith<TResult> (continuationFunction, state, CancellationToken.None, TaskContinuationOptions.None, scheduler);
  707. }
  708. public Task<TResult> ContinueWith<TResult> (Func<Task, object, TResult> continuationFunction, object state, CancellationToken cancellationToken,
  709. TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
  710. {
  711. if (continuationFunction == null)
  712. throw new ArgumentNullException ("continuationFunction");
  713. if (scheduler == null)
  714. throw new ArgumentNullException ("scheduler");
  715. var t = new Task<TResult> (l => continuationFunction (this, l),
  716. state,
  717. cancellationToken,
  718. GetCreationOptions (continuationOptions),
  719. this);
  720. ContinueWithCore (t, continuationOptions, scheduler);
  721. return t;
  722. }
  723. public static Task<TResult> FromResult<TResult> (TResult result)
  724. {
  725. var tcs = new TaskCompletionSource<TResult> ();
  726. tcs.SetResult (result);
  727. return tcs.Task;
  728. }
  729. public TaskAwaiter GetAwaiter ()
  730. {
  731. return new TaskAwaiter (this);
  732. }
  733. public static Task Run (Action action)
  734. {
  735. return Run (action, CancellationToken.None);
  736. }
  737. public static Task Run (Action action, CancellationToken cancellationToken)
  738. {
  739. if (cancellationToken.IsCancellationRequested)
  740. return TaskConstants.Canceled;
  741. var t = new Task (action, cancellationToken, TaskCreationOptions.DenyChildAttach);
  742. t.Start ();
  743. return t;
  744. }
  745. public static Task Run (Func<Task> function)
  746. {
  747. return Run (function, CancellationToken.None);
  748. }
  749. public static Task Run (Func<Task> function, CancellationToken cancellationToken)
  750. {
  751. if (cancellationToken.IsCancellationRequested)
  752. return TaskConstants.Canceled;
  753. var t = new Task<Task> (function, cancellationToken);
  754. t.Start ();
  755. return t;
  756. }
  757. public static Task<TResult> Run<TResult> (Func<TResult> function)
  758. {
  759. return Run (function, CancellationToken.None);
  760. }
  761. public static Task<TResult> Run<TResult> (Func<TResult> function, CancellationToken cancellationToken)
  762. {
  763. if (cancellationToken.IsCancellationRequested)
  764. return TaskConstants<TResult>.Canceled;
  765. var t = new Task<TResult> (function, cancellationToken, TaskCreationOptions.DenyChildAttach);
  766. t.Start ();
  767. return t;
  768. }
  769. public static Task<TResult> Run<TResult> (Func<Task<TResult>> function)
  770. {
  771. return Run (function, CancellationToken.None);
  772. }
  773. public static Task<TResult> Run<TResult> (Func<Task<TResult>> function, CancellationToken cancellationToken)
  774. {
  775. if (cancellationToken.IsCancellationRequested)
  776. return TaskConstants<TResult>.Canceled;
  777. var t = Task<Task<TResult>>.Factory.StartNew (function, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
  778. return GetTaskResult (t);
  779. }
  780. async static Task<TResult> GetTaskResult<TResult> (Task<Task<TResult>> task)
  781. {
  782. var r = await task.ConfigureAwait (false);
  783. return r.Result;
  784. }
  785. public static YieldAwaitable Yield ()
  786. {
  787. return new YieldAwaitable ();
  788. }
  789. #endif
  790. #region Properties
  791. public static TaskFactory Factory {
  792. get {
  793. return defaultFactory;
  794. }
  795. }
  796. public static int? CurrentId {
  797. get {
  798. Task t = current;
  799. return t == null ? (int?)null : t.Id;
  800. }
  801. }
  802. public AggregateException Exception {
  803. get {
  804. exceptionObserved = true;
  805. return exception;
  806. }
  807. internal set {
  808. exception = value;
  809. }
  810. }
  811. public bool IsCanceled {
  812. get {
  813. return status == TaskStatus.Canceled;
  814. }
  815. }
  816. public bool IsCompleted {
  817. get {
  818. return status >= TaskStatus.RanToCompletion;
  819. }
  820. }
  821. public bool IsFaulted {
  822. get {
  823. return status == TaskStatus.Faulted;
  824. }
  825. }
  826. public TaskCreationOptions CreationOptions {
  827. get {
  828. return taskCreationOptions;
  829. }
  830. }
  831. public TaskStatus Status {
  832. get {
  833. return status;
  834. }
  835. internal set {
  836. status = value;
  837. }
  838. }
  839. public object AsyncState {
  840. get {
  841. return state;
  842. }
  843. }
  844. bool IAsyncResult.CompletedSynchronously {
  845. get {
  846. return true;
  847. }
  848. }
  849. WaitHandle IAsyncResult.AsyncWaitHandle {
  850. get {
  851. return null;
  852. }
  853. }
  854. public int Id {
  855. get {
  856. return taskId;
  857. }
  858. }
  859. internal Task Parent {
  860. get {
  861. return parent;
  862. }
  863. }
  864. internal string DisplayActionMethod {
  865. get {
  866. Delegate d = simpleAction ?? (Delegate) action;
  867. return d == null ? "<none>" : d.Method.ToString ();
  868. }
  869. }
  870. #endregion
  871. }
  872. }
  873. #endif