Task.cs 31 KB

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