Task.cs 21 KB

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