Task.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029
  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.Runtime.CompilerServices;
  34. namespace System.Threading.Tasks
  35. {
  36. [System.Diagnostics.DebuggerDisplay ("Id = {Id}, Status = {Status}")]
  37. [System.Diagnostics.DebuggerTypeProxy (typeof (TaskDebuggerView))]
  38. public class Task : IDisposable, IAsyncResult
  39. {
  40. // With this attribute each thread has its own value so that it's correct for our Schedule code
  41. // and for Parent property.
  42. [System.ThreadStatic]
  43. static Task current;
  44. [System.ThreadStatic]
  45. static Action<Task> childWorkAdder;
  46. Task parent;
  47. static int id = -1;
  48. static readonly TaskFactory defaultFactory = new TaskFactory ();
  49. internal static readonly Task Finished = new Task (TaskStatus.RanToCompletion);
  50. internal static readonly Task Canceled = new Task (TaskStatus.Canceled);
  51. CountdownEvent childTasks = new CountdownEvent (1);
  52. int taskId;
  53. TaskCreationOptions taskCreationOptions;
  54. TaskScheduler scheduler;
  55. ManualResetEventSlim schedWait = new ManualResetEventSlim (false);
  56. volatile AggregateException exception;
  57. volatile bool exceptionObserved;
  58. ConcurrentQueue<AggregateException> childExceptions;
  59. TaskStatus status;
  60. Action<object> action;
  61. Action simpleAction;
  62. object state;
  63. AtomicBooleanValue executing;
  64. ConcurrentQueue<EventHandler> completed;
  65. CancellationToken token;
  66. const TaskCreationOptions MaxTaskCreationOptions =
  67. TaskCreationOptions.PreferFairness | TaskCreationOptions.LongRunning | TaskCreationOptions.AttachedToParent;
  68. public Task (Action action) : this (action, TaskCreationOptions.None)
  69. {
  70. }
  71. public Task (Action action, TaskCreationOptions creationOptions) : this (action, CancellationToken.None, creationOptions)
  72. {
  73. }
  74. public Task (Action action, CancellationToken cancellationToken) : this (action, cancellationToken, TaskCreationOptions.None)
  75. {
  76. }
  77. public Task (Action action, CancellationToken cancellationToken, TaskCreationOptions creationOptions)
  78. : this (null, null, cancellationToken, creationOptions, current)
  79. {
  80. if (action == null)
  81. throw new ArgumentNullException ("action");
  82. if (creationOptions > MaxTaskCreationOptions || creationOptions < TaskCreationOptions.None)
  83. throw new ArgumentOutOfRangeException ("creationOptions");
  84. this.simpleAction = action;
  85. }
  86. public Task (Action<object> action, object state) : this (action, state, TaskCreationOptions.None)
  87. {
  88. }
  89. public Task (Action<object> action, object state, TaskCreationOptions creationOptions)
  90. : this (action, state, CancellationToken.None, creationOptions)
  91. {
  92. }
  93. public Task (Action<object> action, object state, CancellationToken cancellationToken)
  94. : this (action, state, cancellationToken, TaskCreationOptions.None)
  95. {
  96. }
  97. public Task (Action<object> action, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions)
  98. : this (action, state, cancellationToken, creationOptions, current)
  99. {
  100. if (action == null)
  101. throw new ArgumentNullException ("action");
  102. if (creationOptions > MaxTaskCreationOptions || creationOptions < TaskCreationOptions.None)
  103. throw new ArgumentOutOfRangeException ("creationOptions");
  104. }
  105. internal Task (Action<object> action,
  106. object state,
  107. CancellationToken cancellationToken,
  108. TaskCreationOptions creationOptions,
  109. Task parent)
  110. {
  111. this.taskCreationOptions = creationOptions;
  112. this.action = action;
  113. this.state = state;
  114. this.taskId = Interlocked.Increment (ref id);
  115. this.status = cancellationToken.IsCancellationRequested ? TaskStatus.Canceled : TaskStatus.Created;
  116. this.token = cancellationToken;
  117. this.parent = parent;
  118. // Process taskCreationOptions
  119. if (CheckTaskOptions (taskCreationOptions, TaskCreationOptions.AttachedToParent) && parent != null)
  120. parent.AddChild ();
  121. }
  122. internal Task (TaskStatus status)
  123. {
  124. this.status = status;
  125. }
  126. ~Task ()
  127. {
  128. if (exception != null && !exceptionObserved)
  129. throw exception;
  130. }
  131. bool CheckTaskOptions (TaskCreationOptions opt, TaskCreationOptions member)
  132. {
  133. return (opt & member) == member;
  134. }
  135. #region Start
  136. public void Start ()
  137. {
  138. Start (TaskScheduler.Current);
  139. }
  140. public void Start (TaskScheduler scheduler)
  141. {
  142. if (status >= TaskStatus.WaitingToRun)
  143. throw new InvalidOperationException ("The Task is not in a valid state to be started.");
  144. SetupScheduler (scheduler);
  145. Schedule ();
  146. }
  147. internal void SetupScheduler (TaskScheduler scheduler)
  148. {
  149. this.scheduler = scheduler;
  150. status = TaskStatus.WaitingForActivation;
  151. schedWait.Set ();
  152. }
  153. public void RunSynchronously ()
  154. {
  155. RunSynchronously (TaskScheduler.Current);
  156. }
  157. public void RunSynchronously (TaskScheduler scheduler)
  158. {
  159. if (scheduler == null)
  160. throw new ArgumentNullException ("scheduler");
  161. if (Status > TaskStatus.WaitingForActivation)
  162. throw new InvalidOperationException ("The task is not in a valid state to be started");
  163. SetupScheduler (scheduler);
  164. var saveStatus = status;
  165. status = TaskStatus.WaitingToRun;
  166. try {
  167. if (scheduler.RunInline (this))
  168. return;
  169. } catch (Exception inner) {
  170. throw new TaskSchedulerException (inner);
  171. }
  172. status = saveStatus;
  173. Start (scheduler);
  174. Wait ();
  175. }
  176. #endregion
  177. #region ContinueWith
  178. public Task ContinueWith (Action<Task> continuationAction)
  179. {
  180. return ContinueWith (continuationAction, TaskContinuationOptions.None);
  181. }
  182. public Task ContinueWith (Action<Task> continuationAction, TaskContinuationOptions continuationOptions)
  183. {
  184. return ContinueWith (continuationAction, CancellationToken.None, continuationOptions, TaskScheduler.Current);
  185. }
  186. public Task ContinueWith (Action<Task> continuationAction, CancellationToken cancellationToken)
  187. {
  188. return ContinueWith (continuationAction, cancellationToken, TaskContinuationOptions.None, TaskScheduler.Current);
  189. }
  190. public Task ContinueWith (Action<Task> continuationAction, TaskScheduler scheduler)
  191. {
  192. return ContinueWith (continuationAction, CancellationToken.None, TaskContinuationOptions.None, scheduler);
  193. }
  194. public Task ContinueWith (Action<Task> continuationAction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
  195. {
  196. if (continuationAction == null)
  197. throw new ArgumentNullException ("continuationAction");
  198. if (scheduler == null)
  199. throw new ArgumentNullException ("scheduler");
  200. Task continuation = new Task (l => continuationAction ((Task)l),
  201. this,
  202. cancellationToken,
  203. GetCreationOptions (continuationOptions),
  204. this);
  205. ContinueWithCore (continuation, continuationOptions, scheduler);
  206. return continuation;
  207. }
  208. public Task<TResult> ContinueWith<TResult> (Func<Task, TResult> continuationFunction)
  209. {
  210. return ContinueWith<TResult> (continuationFunction, TaskContinuationOptions.None);
  211. }
  212. public Task<TResult> ContinueWith<TResult> (Func<Task, TResult> continuationFunction, TaskContinuationOptions continuationOptions)
  213. {
  214. return ContinueWith<TResult> (continuationFunction, CancellationToken.None, continuationOptions, TaskScheduler.Current);
  215. }
  216. public Task<TResult> ContinueWith<TResult> (Func<Task, TResult> continuationFunction, CancellationToken cancellationToken)
  217. {
  218. return ContinueWith<TResult> (continuationFunction, cancellationToken, TaskContinuationOptions.None, TaskScheduler.Current);
  219. }
  220. public Task<TResult> ContinueWith<TResult> (Func<Task, TResult> continuationFunction, TaskScheduler scheduler)
  221. {
  222. return ContinueWith<TResult> (continuationFunction, CancellationToken.None, TaskContinuationOptions.None, scheduler);
  223. }
  224. public Task<TResult> ContinueWith<TResult> (Func<Task, TResult> continuationFunction, CancellationToken cancellationToken,
  225. TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
  226. {
  227. if (continuationFunction == null)
  228. throw new ArgumentNullException ("continuationFunction");
  229. if (scheduler == null)
  230. throw new ArgumentNullException ("scheduler");
  231. Task<TResult> t = new Task<TResult> ((o) => continuationFunction ((Task)o),
  232. this,
  233. cancellationToken,
  234. GetCreationOptions (continuationOptions),
  235. this);
  236. ContinueWithCore (t, continuationOptions, scheduler);
  237. return t;
  238. }
  239. internal void ContinueWithCore (Task continuation, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
  240. {
  241. ContinueWithCore (continuation, continuationOptions, scheduler, null);
  242. }
  243. internal void ContinueWithCore (Task continuation, TaskContinuationOptions kind,
  244. TaskScheduler scheduler, Func<bool> predicate)
  245. {
  246. // Already set the scheduler so that user can call Wait and that sort of stuff
  247. continuation.scheduler = scheduler;
  248. continuation.schedWait.Set ();
  249. continuation.status = TaskStatus.WaitingForActivation;
  250. AtomicBoolean launched = new AtomicBoolean ();
  251. EventHandler action = delegate (object sender, EventArgs e) {
  252. if (launched.TryRelaxedSet ()) {
  253. if (predicate != null && !predicate ())
  254. return;
  255. if (!ContinuationStatusCheck (kind)) {
  256. continuation.CancelReal ();
  257. continuation.Dispose ();
  258. return;
  259. }
  260. CheckAndSchedule (continuation, kind, scheduler, sender == null);
  261. }
  262. };
  263. if (IsCompleted) {
  264. action (null, EventArgs.Empty);
  265. return;
  266. }
  267. if (completed == null)
  268. Interlocked.CompareExchange (ref completed, new ConcurrentQueue<EventHandler> (), null);
  269. completed.Enqueue (action);
  270. // Retry in case completion was achieved but event adding was too late
  271. if (IsCompleted)
  272. action (null, EventArgs.Empty);
  273. }
  274. bool ContinuationStatusCheck (TaskContinuationOptions kind)
  275. {
  276. if (kind == TaskContinuationOptions.None)
  277. return true;
  278. int kindCode = (int)kind;
  279. if (kindCode >= ((int)TaskContinuationOptions.NotOnRanToCompletion)) {
  280. // Remove other options
  281. kind &= ~(TaskContinuationOptions.PreferFairness
  282. | TaskContinuationOptions.LongRunning
  283. | TaskContinuationOptions.AttachedToParent
  284. | TaskContinuationOptions.ExecuteSynchronously);
  285. if (status == TaskStatus.Canceled) {
  286. if (kind == TaskContinuationOptions.NotOnCanceled)
  287. return false;
  288. if (kind == TaskContinuationOptions.OnlyOnFaulted)
  289. return false;
  290. if (kind == TaskContinuationOptions.OnlyOnRanToCompletion)
  291. return false;
  292. } else if (status == TaskStatus.Faulted) {
  293. if (kind == TaskContinuationOptions.NotOnFaulted)
  294. return false;
  295. if (kind == TaskContinuationOptions.OnlyOnCanceled)
  296. return false;
  297. if (kind == TaskContinuationOptions.OnlyOnRanToCompletion)
  298. return false;
  299. } else if (status == TaskStatus.RanToCompletion) {
  300. if (kind == TaskContinuationOptions.NotOnRanToCompletion)
  301. return false;
  302. if (kind == TaskContinuationOptions.OnlyOnFaulted)
  303. return false;
  304. if (kind == TaskContinuationOptions.OnlyOnCanceled)
  305. return false;
  306. }
  307. }
  308. return true;
  309. }
  310. void CheckAndSchedule (Task continuation, TaskContinuationOptions options, TaskScheduler scheduler, bool fromCaller)
  311. {
  312. if ((options & TaskContinuationOptions.ExecuteSynchronously) > 0)
  313. continuation.RunSynchronously (scheduler);
  314. else
  315. continuation.Start (scheduler);
  316. }
  317. internal TaskCreationOptions GetCreationOptions (TaskContinuationOptions kind)
  318. {
  319. TaskCreationOptions options = TaskCreationOptions.None;
  320. if ((kind & TaskContinuationOptions.AttachedToParent) > 0)
  321. options |= TaskCreationOptions.AttachedToParent;
  322. if ((kind & TaskContinuationOptions.PreferFairness) > 0)
  323. options |= TaskCreationOptions.PreferFairness;
  324. if ((kind & TaskContinuationOptions.LongRunning) > 0)
  325. options |= TaskCreationOptions.LongRunning;
  326. return options;
  327. }
  328. #endregion
  329. #region Internal and protected thingies
  330. internal void Schedule ()
  331. {
  332. status = TaskStatus.WaitingToRun;
  333. // If worker is null it means it is a local one, revert to the old behavior
  334. // If TaskScheduler.Current is not being used, the scheduler was explicitly provided, so we must use that
  335. if (scheduler != TaskScheduler.Current || childWorkAdder == null || CheckTaskOptions (taskCreationOptions, TaskCreationOptions.PreferFairness)) {
  336. scheduler.QueueTask (this);
  337. } else {
  338. /* Like the semantic of the ABP paper describe it, we add ourselves to the bottom
  339. * of our Parent Task's ThreadWorker deque. It's ok to do that since we are in
  340. * the correct Thread during the creation
  341. */
  342. childWorkAdder (this);
  343. }
  344. }
  345. void ThreadStart ()
  346. {
  347. /* Allow scheduler to break fairness of deque ordering without
  348. * breaking its semantic (the task can be executed twice but the
  349. * second time it will return immediately
  350. */
  351. if (!executing.TryRelaxedSet ())
  352. return;
  353. current = this;
  354. TaskScheduler.Current = scheduler;
  355. if (!token.IsCancellationRequested) {
  356. status = TaskStatus.Running;
  357. try {
  358. InnerInvoke ();
  359. } catch (OperationCanceledException oce) {
  360. if (token != CancellationToken.None && oce.CancellationToken == token)
  361. CancelReal ();
  362. else
  363. HandleGenericException (oce);
  364. } catch (Exception e) {
  365. HandleGenericException (e);
  366. }
  367. } else {
  368. CancelReal ();
  369. }
  370. Finish ();
  371. }
  372. internal void Execute (Action<Task> childAdder)
  373. {
  374. childWorkAdder = childAdder;
  375. ThreadStart ();
  376. }
  377. internal void AddChild ()
  378. {
  379. childTasks.AddCount ();
  380. }
  381. internal void ChildCompleted (AggregateException childEx)
  382. {
  383. if (childEx != null) {
  384. if (childExceptions == null)
  385. Interlocked.CompareExchange (ref childExceptions, new ConcurrentQueue<AggregateException> (), null);
  386. childExceptions.Enqueue (childEx);
  387. }
  388. if (childTasks.Signal () && status == TaskStatus.WaitingForChildrenToComplete) {
  389. status = TaskStatus.RanToCompletion;
  390. ProcessChildExceptions ();
  391. ProcessCompleteDelegates ();
  392. }
  393. }
  394. internal virtual void InnerInvoke ()
  395. {
  396. if (action == null && simpleAction != null)
  397. simpleAction ();
  398. else if (action != null)
  399. action (state);
  400. // Set action to null so that the GC can collect the delegate and thus
  401. // any big object references that the user might have captured in an anonymous method
  402. action = null;
  403. simpleAction = null;
  404. state = null;
  405. }
  406. internal void Finish ()
  407. {
  408. // If there wasn't any child created in the task we set the CountdownEvent
  409. childTasks.Signal ();
  410. // Don't override Canceled or Faulted
  411. if (status == TaskStatus.Running) {
  412. if (childTasks.IsSet)
  413. status = TaskStatus.RanToCompletion;
  414. else
  415. status = TaskStatus.WaitingForChildrenToComplete;
  416. }
  417. if (status != TaskStatus.WaitingForChildrenToComplete)
  418. ProcessCompleteDelegates ();
  419. // Reset the current thingies
  420. current = null;
  421. TaskScheduler.Current = null;
  422. // Tell parent that we are finished
  423. if (CheckTaskOptions (taskCreationOptions, TaskCreationOptions.AttachedToParent) && parent != null) {
  424. parent.ChildCompleted (this.Exception);
  425. }
  426. }
  427. void ProcessCompleteDelegates ()
  428. {
  429. if (completed == null)
  430. return;
  431. EventHandler handler;
  432. while (completed.TryDequeue (out handler))
  433. handler (this, EventArgs.Empty);
  434. }
  435. void ProcessChildExceptions ()
  436. {
  437. if (childExceptions == null)
  438. return;
  439. if (exception == null)
  440. exception = new AggregateException ();
  441. AggregateException childEx;
  442. while (childExceptions.TryDequeue (out childEx))
  443. exception.AddChildException (childEx);
  444. }
  445. #endregion
  446. #region Cancel and Wait related method
  447. internal void CancelReal ()
  448. {
  449. status = TaskStatus.Canceled;
  450. }
  451. internal void HandleGenericException (Exception e)
  452. {
  453. HandleGenericException (new AggregateException (e));
  454. }
  455. internal void HandleGenericException (AggregateException e)
  456. {
  457. exception = e;
  458. Thread.MemoryBarrier ();
  459. status = TaskStatus.Faulted;
  460. if (scheduler != null && scheduler.FireUnobservedEvent (exception).Observed)
  461. exceptionObserved = true;
  462. }
  463. public void Wait ()
  464. {
  465. if (scheduler == null)
  466. schedWait.Wait ();
  467. if (!IsCompleted)
  468. scheduler.ParticipateUntil (this);
  469. if (exception != null)
  470. throw exception;
  471. if (IsCanceled)
  472. throw new AggregateException (new TaskCanceledException (this));
  473. }
  474. public void Wait (CancellationToken cancellationToken)
  475. {
  476. Wait (-1, cancellationToken);
  477. }
  478. public bool Wait (TimeSpan timeout)
  479. {
  480. return Wait (CheckTimeout (timeout), CancellationToken.None);
  481. }
  482. public bool Wait (int millisecondsTimeout)
  483. {
  484. return Wait (millisecondsTimeout, CancellationToken.None);
  485. }
  486. public bool Wait (int millisecondsTimeout, CancellationToken cancellationToken)
  487. {
  488. if (millisecondsTimeout < -1)
  489. throw new ArgumentOutOfRangeException ("millisecondsTimeout");
  490. if (millisecondsTimeout == -1 && token == CancellationToken.None) {
  491. Wait ();
  492. return true;
  493. }
  494. Watch watch = Watch.StartNew ();
  495. if (scheduler == null) {
  496. schedWait.Wait (millisecondsTimeout, cancellationToken);
  497. millisecondsTimeout = ComputeTimeout (millisecondsTimeout, watch);
  498. }
  499. ManualResetEventSlim predicateEvt = new ManualResetEventSlim (false);
  500. if (cancellationToken != CancellationToken.None) {
  501. cancellationToken.Register (predicateEvt.Set);
  502. cancellationToken.ThrowIfCancellationRequested ();
  503. }
  504. bool result = scheduler.ParticipateUntil (this, predicateEvt, millisecondsTimeout);
  505. if (exception != null)
  506. throw exception;
  507. if (IsCanceled)
  508. throw new AggregateException (new TaskCanceledException (this));
  509. return !result;
  510. }
  511. public static void WaitAll (params Task[] tasks)
  512. {
  513. if (tasks == null)
  514. throw new ArgumentNullException ("tasks");
  515. foreach (var t in tasks) {
  516. if (t == null)
  517. throw new ArgumentNullException ("tasks", "the tasks argument contains a null element");
  518. t.Wait ();
  519. }
  520. }
  521. public static void WaitAll (Task[] tasks, CancellationToken cancellationToken)
  522. {
  523. if (tasks == null)
  524. throw new ArgumentNullException ("tasks");
  525. foreach (var t in tasks) {
  526. if (t == null)
  527. throw new ArgumentNullException ("tasks", "the tasks argument contains a null element");
  528. t.Wait (cancellationToken);
  529. }
  530. }
  531. public static bool WaitAll (Task[] tasks, TimeSpan timeout)
  532. {
  533. if (tasks == null)
  534. throw new ArgumentNullException ("tasks");
  535. bool result = true;
  536. foreach (var t in tasks) {
  537. if (t == null)
  538. throw new ArgumentNullException ("tasks", "the tasks argument contains a null element");
  539. result &= t.Wait (timeout);
  540. }
  541. return result;
  542. }
  543. public static bool WaitAll (Task[] tasks, int millisecondsTimeout)
  544. {
  545. if (tasks == null)
  546. throw new ArgumentNullException ("tasks");
  547. bool result = true;
  548. foreach (var t in tasks) {
  549. if (t == null)
  550. throw new ArgumentNullException ("tasks", "the tasks argument contains a null element");
  551. result &= t.Wait (millisecondsTimeout);
  552. }
  553. return result;
  554. }
  555. public static bool WaitAll (Task[] tasks, int millisecondsTimeout, CancellationToken cancellationToken)
  556. {
  557. if (tasks == null)
  558. throw new ArgumentNullException ("tasks");
  559. bool result = true;
  560. foreach (var t in tasks) {
  561. if (t == null)
  562. throw new ArgumentNullException ("tasks", "the tasks argument contains a null element");
  563. result &= t.Wait (millisecondsTimeout, cancellationToken);
  564. }
  565. return result;
  566. }
  567. public static int WaitAny (params Task[] tasks)
  568. {
  569. return WaitAny (tasks, -1, CancellationToken.None);
  570. }
  571. public static int WaitAny (Task[] tasks, TimeSpan timeout)
  572. {
  573. return WaitAny (tasks, CheckTimeout (timeout));
  574. }
  575. public static int WaitAny (Task[] tasks, int millisecondsTimeout)
  576. {
  577. if (millisecondsTimeout < -1)
  578. throw new ArgumentOutOfRangeException ("millisecondsTimeout");
  579. if (millisecondsTimeout == -1)
  580. return WaitAny (tasks);
  581. return WaitAny (tasks, millisecondsTimeout, CancellationToken.None);
  582. }
  583. public static int WaitAny (Task[] tasks, CancellationToken cancellationToken)
  584. {
  585. return WaitAny (tasks, -1, cancellationToken);
  586. }
  587. public static int WaitAny (Task[] tasks, int millisecondsTimeout, CancellationToken cancellationToken)
  588. {
  589. if (tasks == null)
  590. throw new ArgumentNullException ("tasks");
  591. if (tasks.Length == 0)
  592. throw new ArgumentException ("tasks is empty", "tasks");
  593. if (tasks.Length == 1) {
  594. tasks[0].Wait (millisecondsTimeout, cancellationToken);
  595. return 0;
  596. }
  597. int numFinished = 0;
  598. int indexFirstFinished = -1;
  599. int index = 0;
  600. TaskScheduler sched = null;
  601. Task task = null;
  602. Watch watch = Watch.StartNew ();
  603. ManualResetEventSlim predicateEvt = new ManualResetEventSlim (false);
  604. foreach (Task t in tasks) {
  605. int indexResult = index++;
  606. t.ContinueWith (delegate {
  607. if (numFinished >= 1)
  608. return;
  609. int result = Interlocked.Increment (ref numFinished);
  610. // Check if we are the first to have finished
  611. if (result == 1)
  612. indexFirstFinished = indexResult;
  613. // Stop waiting
  614. predicateEvt.Set ();
  615. }, TaskContinuationOptions.ExecuteSynchronously);
  616. if (sched == null && t.scheduler != null) {
  617. task = t;
  618. sched = t.scheduler;
  619. }
  620. }
  621. // If none of task have a scheduler we are forced to wait for at least one to start
  622. if (sched == null) {
  623. var handles = Array.ConvertAll (tasks, t => t.schedWait.WaitHandle);
  624. int shandle = -1;
  625. if ((shandle = WaitHandle.WaitAny (handles, millisecondsTimeout)) == WaitHandle.WaitTimeout)
  626. return -1;
  627. sched = tasks[shandle].scheduler;
  628. task = tasks[shandle];
  629. millisecondsTimeout = ComputeTimeout (millisecondsTimeout, watch);
  630. }
  631. // One task already finished
  632. if (indexFirstFinished != -1)
  633. return indexFirstFinished;
  634. if (cancellationToken != CancellationToken.None) {
  635. cancellationToken.Register (predicateEvt.Set);
  636. cancellationToken.ThrowIfCancellationRequested ();
  637. }
  638. sched.ParticipateUntil (task, predicateEvt, millisecondsTimeout);
  639. // Index update is still not done
  640. if (indexFirstFinished == -1) {
  641. SpinWait wait = new SpinWait ();
  642. while (indexFirstFinished == -1)
  643. wait.SpinOnce ();
  644. }
  645. return indexFirstFinished;
  646. }
  647. static int CheckTimeout (TimeSpan timeout)
  648. {
  649. try {
  650. return checked ((int)timeout.TotalMilliseconds);
  651. } catch (System.OverflowException) {
  652. throw new ArgumentOutOfRangeException ("timeout");
  653. }
  654. }
  655. static int ComputeTimeout (int millisecondsTimeout, Watch watch)
  656. {
  657. return millisecondsTimeout == -1 ? -1 : (int)Math.Max (watch.ElapsedMilliseconds - millisecondsTimeout, 1);
  658. }
  659. #endregion
  660. #region Dispose
  661. public void Dispose ()
  662. {
  663. Dispose (true);
  664. }
  665. protected virtual void Dispose (bool disposing)
  666. {
  667. if (!IsCompleted)
  668. throw new InvalidOperationException ("A task may only be disposed if it is in a completion state");
  669. // Set action to null so that the GC can collect the delegate and thus
  670. // any big object references that the user might have captured in a anonymous method
  671. if (disposing) {
  672. action = null;
  673. state = null;
  674. }
  675. }
  676. #endregion
  677. #if NET_4_5
  678. public ConfiguredTaskAwaitable ConfigureAwait (bool continueOnCapturedContext)
  679. {
  680. return new ConfiguredTaskAwaitable (this, continueOnCapturedContext);
  681. }
  682. public Task ContinueWith (Action<Task, object> continuationAction, object state)
  683. {
  684. return ContinueWith (continuationAction, state, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Current);
  685. }
  686. public Task ContinueWith (Action<Task, object> continuationAction, object state, CancellationToken cancellationToken)
  687. {
  688. return ContinueWith (continuationAction, state, cancellationToken, TaskContinuationOptions.None, TaskScheduler.Current);
  689. }
  690. public Task ContinueWith (Action<Task, object> continuationAction, object state, TaskContinuationOptions continuationOptions)
  691. {
  692. return ContinueWith (continuationAction, state, CancellationToken.None, continuationOptions, TaskScheduler.Current);
  693. }
  694. public Task ContinueWith (Action<Task, object> continuationAction, object state, TaskScheduler scheduler)
  695. {
  696. return ContinueWith (continuationAction, state, CancellationToken.None, TaskContinuationOptions.None, scheduler);
  697. }
  698. public Task ContinueWith (Action<Task, object> continuationAction, object state, CancellationToken cancellationToken,
  699. TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
  700. {
  701. if (continuationAction == null)
  702. throw new ArgumentNullException ("continuationAction");
  703. if (scheduler == null)
  704. throw new ArgumentNullException ("scheduler");
  705. Task continuation = new Task (l => continuationAction (this, l), state,
  706. cancellationToken,
  707. GetCreationOptions (continuationOptions),
  708. this);
  709. ContinueWithCore (continuation, continuationOptions, scheduler);
  710. return continuation;
  711. }
  712. public Task<TResult> ContinueWith<TResult> (Func<Task, object, TResult> continuationFunction, object state)
  713. {
  714. return ContinueWith<TResult> (continuationFunction, state, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Current);
  715. }
  716. public Task<TResult> ContinueWith<TResult> (Func<Task, object, TResult> continuationFunction, object state, TaskContinuationOptions continuationOptions)
  717. {
  718. return ContinueWith<TResult> (continuationFunction, state, CancellationToken.None, continuationOptions, TaskScheduler.Current);
  719. }
  720. public Task<TResult> ContinueWith<TResult> (Func<Task, object, TResult> continuationFunction, object state, CancellationToken cancellationToken)
  721. {
  722. return ContinueWith<TResult> (continuationFunction, state, cancellationToken, TaskContinuationOptions.None, TaskScheduler.Current);
  723. }
  724. public Task<TResult> ContinueWith<TResult> (Func<Task, object, TResult> continuationFunction, object state, TaskScheduler scheduler)
  725. {
  726. return ContinueWith<TResult> (continuationFunction, state, CancellationToken.None, TaskContinuationOptions.None, scheduler);
  727. }
  728. public Task<TResult> ContinueWith<TResult> (Func<Task, object, TResult> continuationFunction, object state, CancellationToken cancellationToken,
  729. TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
  730. {
  731. if (continuationFunction == null)
  732. throw new ArgumentNullException ("continuationFunction");
  733. if (scheduler == null)
  734. throw new ArgumentNullException ("scheduler");
  735. var t = new Task<TResult> (l => continuationFunction (this, l),
  736. state,
  737. cancellationToken,
  738. GetCreationOptions (continuationOptions),
  739. this);
  740. ContinueWithCore (t, continuationOptions, scheduler);
  741. return t;
  742. }
  743. public static Task<TResult> FromResult<TResult> (TResult result)
  744. {
  745. var t = new Task<TResult> (TaskStatus.RanToCompletion);
  746. t.Result = result;
  747. return t;
  748. }
  749. public TaskAwaiter GetAwaiter ()
  750. {
  751. return new TaskAwaiter (this);
  752. }
  753. public static YieldAwaitable Yield ()
  754. {
  755. return new YieldAwaitable ();
  756. }
  757. #endif
  758. #region Properties
  759. public static TaskFactory Factory {
  760. get {
  761. return defaultFactory;
  762. }
  763. }
  764. public static int? CurrentId {
  765. get {
  766. Task t = current;
  767. return t == null ? (int?)null : t.Id;
  768. }
  769. }
  770. public AggregateException Exception {
  771. get {
  772. exceptionObserved = true;
  773. return exception;
  774. }
  775. internal set {
  776. exception = value;
  777. }
  778. }
  779. public bool IsCanceled {
  780. get {
  781. return status == TaskStatus.Canceled;
  782. }
  783. }
  784. public bool IsCompleted {
  785. get {
  786. return status == TaskStatus.RanToCompletion ||
  787. status == TaskStatus.Canceled || status == TaskStatus.Faulted;
  788. }
  789. }
  790. public bool IsFaulted {
  791. get {
  792. return status == TaskStatus.Faulted;
  793. }
  794. }
  795. public TaskCreationOptions CreationOptions {
  796. get {
  797. return taskCreationOptions;
  798. }
  799. }
  800. public TaskStatus Status {
  801. get {
  802. return status;
  803. }
  804. internal set {
  805. status = value;
  806. }
  807. }
  808. public object AsyncState {
  809. get {
  810. return state;
  811. }
  812. }
  813. bool IAsyncResult.CompletedSynchronously {
  814. get {
  815. return true;
  816. }
  817. }
  818. WaitHandle IAsyncResult.AsyncWaitHandle {
  819. get {
  820. return null;
  821. }
  822. }
  823. public int Id {
  824. get {
  825. return taskId;
  826. }
  827. }
  828. internal Task Parent {
  829. get {
  830. return parent;
  831. }
  832. }
  833. internal string DisplayActionMethod {
  834. get {
  835. Delegate d = simpleAction ?? (Delegate) action;
  836. return d == null ? "<none>" : d.Method.ToString ();
  837. }
  838. }
  839. #endregion
  840. }
  841. }
  842. #endif