Task.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733
  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. volatile AggregateException exception;
  47. volatile bool exceptionObserved;
  48. volatile TaskStatus status;
  49. Action<object> action;
  50. object state;
  51. EventHandler completed;
  52. CancellationToken token;
  53. public Task (Action action) : this (action, TaskCreationOptions.None)
  54. {
  55. }
  56. public Task (Action action, TaskCreationOptions options) : this (action, CancellationToken.None, options)
  57. {
  58. }
  59. public Task (Action action, CancellationToken token) : this (action, token, TaskCreationOptions.None)
  60. {
  61. }
  62. public Task (Action action, CancellationToken token, TaskCreationOptions options)
  63. : this ((o) => { if (action != null) action (); }, null, token, options)
  64. {
  65. }
  66. public Task (Action<object> action, object state) : this (action, state, TaskCreationOptions.None)
  67. {
  68. }
  69. public Task (Action<object> action, object state, TaskCreationOptions options)
  70. : this (action, state, CancellationToken.None, options)
  71. {
  72. }
  73. public Task (Action<object> action, object state, CancellationToken token)
  74. : this (action, state, token, TaskCreationOptions.None)
  75. {
  76. }
  77. public Task (Action<object> action, object state, CancellationToken token, TaskCreationOptions options)
  78. {
  79. this.taskCreationOptions = options;
  80. this.action = action == null ? EmptyFunc : action;
  81. this.state = state;
  82. this.taskId = Interlocked.Increment (ref id);
  83. this.status = TaskStatus.Created;
  84. this.token = token;
  85. // Process taskCreationOptions
  86. if (CheckTaskOptions (taskCreationOptions, TaskCreationOptions.AttachedToParent)) {
  87. parent = current;
  88. if (parent != null)
  89. parent.AddChild ();
  90. }
  91. }
  92. ~Task ()
  93. {
  94. if (exception != null && !exceptionObserved)
  95. throw exception;
  96. }
  97. bool CheckTaskOptions (TaskCreationOptions opt, TaskCreationOptions member)
  98. {
  99. return (opt & member) == member;
  100. }
  101. static void EmptyFunc (object o)
  102. {
  103. }
  104. #region Start
  105. public void Start ()
  106. {
  107. Start (TaskScheduler.Current);
  108. }
  109. public void Start (TaskScheduler tscheduler)
  110. {
  111. this.taskScheduler = tscheduler;
  112. Start (ProxifyScheduler (tscheduler));
  113. }
  114. void Start (IScheduler scheduler)
  115. {
  116. this.scheduler = scheduler;
  117. status = TaskStatus.WaitingForActivation;
  118. Schedule ();
  119. }
  120. IScheduler ProxifyScheduler (TaskScheduler tscheduler)
  121. {
  122. IScheduler sched = tscheduler as IScheduler;
  123. return sched != null ? sched : new SchedulerProxy (tscheduler);
  124. }
  125. public void RunSynchronously ()
  126. {
  127. RunSynchronously (TaskScheduler.Current);
  128. }
  129. public void RunSynchronously (TaskScheduler tscheduler)
  130. {
  131. // Adopt this scheme for the moment
  132. ThreadStart ();
  133. }
  134. #endregion
  135. #region ContinueWith
  136. public Task ContinueWith (Action<Task> a)
  137. {
  138. return ContinueWith (a, TaskContinuationOptions.None);
  139. }
  140. public Task ContinueWith (Action<Task> a, TaskContinuationOptions kind)
  141. {
  142. return ContinueWith (a, CancellationToken.None, kind, TaskScheduler.Current);
  143. }
  144. public Task ContinueWith (Action<Task> a, CancellationToken token)
  145. {
  146. return ContinueWith (a, token, TaskContinuationOptions.None, TaskScheduler.Current);
  147. }
  148. public Task ContinueWith (Action<Task> a, TaskScheduler scheduler)
  149. {
  150. return ContinueWith (a, CancellationToken.None, TaskContinuationOptions.None, scheduler);
  151. }
  152. public Task ContinueWith (Action<Task> a, CancellationToken token, TaskContinuationOptions kind, TaskScheduler scheduler)
  153. {
  154. Task continuation = new Task ((o) => a ((Task)o), this, token, GetCreationOptions (kind));
  155. ContinueWithCore (continuation, kind, scheduler);
  156. return continuation;
  157. }
  158. public Task<TResult> ContinueWith<TResult> (Func<Task, TResult> a)
  159. {
  160. return ContinueWith<TResult> (a, TaskContinuationOptions.None);
  161. }
  162. public Task<TResult> ContinueWith<TResult> (Func<Task, TResult> a, TaskContinuationOptions options)
  163. {
  164. return ContinueWith<TResult> (a, CancellationToken.None, options, TaskScheduler.Current);
  165. }
  166. public Task<TResult> ContinueWith<TResult> (Func<Task, TResult> a, CancellationToken token)
  167. {
  168. return ContinueWith<TResult> (a, token, TaskContinuationOptions.None, TaskScheduler.Current);
  169. }
  170. public Task<TResult> ContinueWith<TResult> (Func<Task, TResult> a, TaskScheduler scheduler)
  171. {
  172. return ContinueWith<TResult> (a, CancellationToken.None, TaskContinuationOptions.None, scheduler);
  173. }
  174. public Task<TResult> ContinueWith<TResult> (Func<Task, TResult> a, CancellationToken token,
  175. TaskContinuationOptions kind, TaskScheduler scheduler)
  176. {
  177. Task<TResult> t = new Task<TResult> ((o) => a ((Task)o), this, token, GetCreationOptions (kind));
  178. ContinueWithCore (t, kind, scheduler);
  179. return t;
  180. }
  181. internal void ContinueWithCore (Task continuation, TaskContinuationOptions kind, TaskScheduler scheduler)
  182. {
  183. ContinueWithCore (continuation, kind, scheduler, () => true);
  184. }
  185. internal void ContinueWithCore (Task continuation, TaskContinuationOptions kind,
  186. TaskScheduler scheduler, Func<bool> predicate)
  187. {
  188. // Already set the scheduler so that user can call Wait and that sort of stuff
  189. continuation.taskScheduler = scheduler;
  190. continuation.scheduler = ProxifyScheduler (scheduler);
  191. AtomicBoolean launched = new AtomicBoolean ();
  192. EventHandler action = delegate (object sender, EventArgs e) {
  193. if (!predicate ()) return;
  194. if (!launched.Value && launched.TrySet ()) {
  195. if (!ContinuationStatusCheck (kind)) {
  196. continuation.CancelReal ();
  197. continuation.Dispose ();
  198. return;
  199. }
  200. CheckAndSchedule (continuation, kind, scheduler, sender == null);
  201. }
  202. };
  203. if (IsCompleted) {
  204. action (null, EventArgs.Empty);
  205. return;
  206. }
  207. completed += action;
  208. // Retry in case completion was achieved but event adding was too late
  209. if (IsCompleted)
  210. action (null, EventArgs.Empty);
  211. }
  212. bool ContinuationStatusCheck (TaskContinuationOptions kind)
  213. {
  214. if (kind == TaskContinuationOptions.None)
  215. return true;
  216. int kindCode = (int)kind;
  217. if (kindCode >= ((int)TaskContinuationOptions.NotOnRanToCompletion)) {
  218. if (status == TaskStatus.Canceled) {
  219. if (kind == TaskContinuationOptions.NotOnCanceled)
  220. return false;
  221. if (kind == TaskContinuationOptions.OnlyOnFaulted)
  222. return false;
  223. if (kind == TaskContinuationOptions.OnlyOnRanToCompletion)
  224. return false;
  225. } else if (status == TaskStatus.Faulted) {
  226. if (kind == TaskContinuationOptions.NotOnFaulted)
  227. return false;
  228. if (kind == TaskContinuationOptions.OnlyOnCanceled)
  229. return false;
  230. if (kind == TaskContinuationOptions.OnlyOnRanToCompletion)
  231. return false;
  232. } else if (status == TaskStatus.RanToCompletion) {
  233. if (kind == TaskContinuationOptions.NotOnRanToCompletion)
  234. return false;
  235. if (kind == TaskContinuationOptions.OnlyOnFaulted)
  236. return false;
  237. if (kind == TaskContinuationOptions.OnlyOnCanceled)
  238. return false;
  239. }
  240. }
  241. return true;
  242. }
  243. void CheckAndSchedule (Task continuation, TaskContinuationOptions options, TaskScheduler scheduler, bool fromCaller)
  244. {
  245. if (!fromCaller
  246. && (options == TaskContinuationOptions.None || (options & TaskContinuationOptions.ExecuteSynchronously) > 0))
  247. continuation.ThreadStart ();
  248. else
  249. continuation.Start (scheduler);
  250. }
  251. internal TaskCreationOptions GetCreationOptions (TaskContinuationOptions kind)
  252. {
  253. TaskCreationOptions options = TaskCreationOptions.None;
  254. if ((kind & TaskContinuationOptions.AttachedToParent) > 0)
  255. options |= TaskCreationOptions.AttachedToParent;
  256. if ((kind & TaskContinuationOptions.PreferFairness) > 0)
  257. options |= TaskCreationOptions.PreferFairness;
  258. if ((kind & TaskContinuationOptions.LongRunning) > 0)
  259. options |= TaskCreationOptions.LongRunning;
  260. return options;
  261. }
  262. #endregion
  263. #region Internal and protected thingies
  264. internal void Schedule ()
  265. {
  266. status = TaskStatus.WaitingToRun;
  267. // If worker is null it means it is a local one, revert to the old behavior
  268. if (childWorkAdder == null || CheckTaskOptions (taskCreationOptions, TaskCreationOptions.PreferFairness)) {
  269. scheduler.AddWork (this);
  270. } else {
  271. /* Like the semantic of the ABP paper describe it, we add ourselves to the bottom
  272. * of our Parent Task's ThreadWorker deque. It's ok to do that since we are in
  273. * the correct Thread during the creation
  274. */
  275. childWorkAdder (this);
  276. }
  277. }
  278. void ThreadStart ()
  279. {
  280. current = this;
  281. TaskScheduler.Current = taskScheduler;
  282. if (!token.IsCancellationRequested) {
  283. status = TaskStatus.Running;
  284. try {
  285. InnerInvoke ();
  286. } catch (Exception e) {
  287. exception = new AggregateException (e);
  288. status = TaskStatus.Faulted;
  289. if (taskScheduler.FireUnobservedEvent (exception).Observed)
  290. exceptionObserved = true;
  291. }
  292. } else {
  293. CancelReal ();
  294. }
  295. Finish ();
  296. }
  297. internal void Execute (Action<Task> childAdder)
  298. {
  299. childWorkAdder = childAdder;
  300. ThreadStart ();
  301. }
  302. internal void AddChild ()
  303. {
  304. childTasks.AddCount ();
  305. }
  306. internal void ChildCompleted ()
  307. {
  308. childTasks.Signal ();
  309. if (childTasks.IsSet && status == TaskStatus.WaitingForChildrenToComplete) {
  310. status = TaskStatus.RanToCompletion;
  311. // Let continuation creation process
  312. EventHandler tempCompleted = completed;
  313. if (tempCompleted != null)
  314. tempCompleted (this, EventArgs.Empty);
  315. }
  316. }
  317. internal virtual void InnerInvoke ()
  318. {
  319. if (action != null)
  320. action (state);
  321. // Set action to null so that the GC can collect the delegate and thus
  322. // any big object references that the user might have captured in an anonymous method
  323. action = null;
  324. state = null;
  325. }
  326. internal void Finish ()
  327. {
  328. // If there wasn't any child created in the task we set the CountdownEvent
  329. childTasks.Signal ();
  330. // Don't override Canceled or Faulted
  331. if (status == TaskStatus.Running) {
  332. if (childTasks.IsSet)
  333. status = TaskStatus.RanToCompletion;
  334. else
  335. status = TaskStatus.WaitingForChildrenToComplete;
  336. }
  337. if (status != TaskStatus.WaitingForChildrenToComplete) {
  338. // Let continuation creation process
  339. EventHandler tempCompleted = completed;
  340. if (tempCompleted != null)
  341. tempCompleted (this, EventArgs.Empty);
  342. }
  343. // Reset the current thingies
  344. current = null;
  345. TaskScheduler.Current = null;
  346. // Tell parent that we are finished
  347. if (CheckTaskOptions (taskCreationOptions, TaskCreationOptions.AttachedToParent) && parent != null){
  348. parent.ChildCompleted ();
  349. }
  350. Dispose ();
  351. }
  352. #endregion
  353. #region Cancel and Wait related method
  354. internal void CancelReal ()
  355. {
  356. exception = new AggregateException (new TaskCanceledException (this));
  357. status = TaskStatus.Canceled;
  358. }
  359. public void Wait ()
  360. {
  361. if (scheduler == null)
  362. throw new InvalidOperationException ("The Task hasn't been Started and thus can't be waited on");
  363. scheduler.ParticipateUntil (this);
  364. if (exception != null)
  365. throw exception;
  366. }
  367. public void Wait (CancellationToken token)
  368. {
  369. Wait (null, token);
  370. }
  371. public bool Wait (TimeSpan ts)
  372. {
  373. return Wait ((int)ts.TotalMilliseconds, CancellationToken.None);
  374. }
  375. public bool Wait (int millisecondsTimeout)
  376. {
  377. return Wait (millisecondsTimeout, CancellationToken.None);
  378. }
  379. public bool Wait (int millisecondsTimeout, CancellationToken token)
  380. {
  381. Watch sw = Watch.StartNew ();
  382. return Wait (() => sw.ElapsedMilliseconds >= millisecondsTimeout, token);
  383. }
  384. bool Wait (Func<bool> stopFunc, CancellationToken token)
  385. {
  386. if (scheduler == null)
  387. throw new InvalidOperationException ("The Task hasn't been Started and thus can't be waited on");
  388. bool result = scheduler.ParticipateUntil (this, delegate {
  389. if (token.IsCancellationRequested)
  390. throw new OperationCanceledException ("The CancellationToken has had cancellation requested.");
  391. return (stopFunc != null) ? stopFunc () : false;
  392. });
  393. if (exception != null)
  394. throw exception;
  395. return !result;
  396. }
  397. public static void WaitAll (params Task[] tasks)
  398. {
  399. if (tasks == null)
  400. throw new ArgumentNullException ("tasks");
  401. if (tasks.Length == 0)
  402. throw new ArgumentException ("tasks is empty", "tasks");
  403. foreach (var t in tasks)
  404. t.Wait ();
  405. }
  406. public static void WaitAll (Task[] tasks, CancellationToken token)
  407. {
  408. if (tasks == null)
  409. throw new ArgumentNullException ("tasks");
  410. if (tasks.Length == 0)
  411. throw new ArgumentException ("tasks is empty", "tasks");
  412. foreach (var t in tasks)
  413. t.Wait (token);
  414. }
  415. public static bool WaitAll (Task[] tasks, TimeSpan ts)
  416. {
  417. if (tasks == null)
  418. throw new ArgumentNullException ("tasks");
  419. if (tasks.Length == 0)
  420. throw new ArgumentException ("tasks is empty", "tasks");
  421. bool result = true;
  422. foreach (var t in tasks)
  423. result &= t.Wait (ts);
  424. return result;
  425. }
  426. public static bool WaitAll (Task[] tasks, int millisecondsTimeout)
  427. {
  428. if (tasks == null)
  429. throw new ArgumentNullException ("tasks");
  430. if (tasks.Length == 0)
  431. throw new ArgumentException ("tasks is empty", "tasks");
  432. bool result = true;
  433. foreach (var t in tasks)
  434. result &= t.Wait (millisecondsTimeout);
  435. return result;
  436. }
  437. public static bool WaitAll (Task[] tasks, int millisecondsTimeout, CancellationToken token)
  438. {
  439. if (tasks == null)
  440. throw new ArgumentNullException ("tasks");
  441. if (tasks.Length == 0)
  442. throw new ArgumentException ("tasks is empty", "tasks");
  443. bool result = true;
  444. foreach (var t in tasks)
  445. result &= t.Wait (millisecondsTimeout, token);
  446. return result;
  447. }
  448. public static int WaitAny (params Task[] tasks)
  449. {
  450. return WaitAny (tasks, null, null);
  451. }
  452. static int WaitAny (Task[] tasks, Func<bool> stopFunc, CancellationToken? token)
  453. {
  454. if (tasks == null)
  455. throw new ArgumentNullException ("tasks");
  456. if (tasks.Length == 0)
  457. throw new ArgumentException ("tasks is empty", "tasks");
  458. int numFinished = 0;
  459. int indexFirstFinished = -1;
  460. int index = 0;
  461. foreach (Task t in tasks) {
  462. t.ContinueWith (delegate {
  463. int indexResult = index;
  464. int result = Interlocked.Increment (ref numFinished);
  465. // Check if we are the first to have finished
  466. if (result == 1)
  467. indexFirstFinished = indexResult;
  468. });
  469. index++;
  470. }
  471. // One task already finished
  472. if (indexFirstFinished != -1)
  473. return indexFirstFinished;
  474. // All tasks are supposed to use the same TaskManager
  475. tasks[0].scheduler.ParticipateUntil (delegate {
  476. if (stopFunc != null && stopFunc ())
  477. return true;
  478. if (token.HasValue && token.Value.IsCancellationRequested)
  479. throw new OperationCanceledException ("The CancellationToken has had cancellation requested.");
  480. return numFinished >= 1;
  481. });
  482. return indexFirstFinished;
  483. }
  484. public static int WaitAny (Task[] tasks, TimeSpan ts)
  485. {
  486. return WaitAny (tasks, (int)ts.TotalMilliseconds);
  487. }
  488. public static int WaitAny (Task[] tasks, int millisecondsTimeout)
  489. {
  490. if (millisecondsTimeout < -1)
  491. throw new ArgumentOutOfRangeException ("millisecondsTimeout");
  492. if (millisecondsTimeout == -1)
  493. return WaitAny (tasks);
  494. Watch sw = Watch.StartNew ();
  495. return WaitAny (tasks, () => sw.ElapsedMilliseconds > millisecondsTimeout, null);
  496. }
  497. public static int WaitAny (Task[] tasks, int millisecondsTimeout, CancellationToken token)
  498. {
  499. if (millisecondsTimeout < -1)
  500. throw new ArgumentOutOfRangeException ("millisecondsTimeout");
  501. if (millisecondsTimeout == -1)
  502. return WaitAny (tasks);
  503. Watch sw = Watch.StartNew ();
  504. return WaitAny (tasks, () => sw.ElapsedMilliseconds > millisecondsTimeout, token);
  505. }
  506. public static int WaitAny (Task[] tasks, CancellationToken token)
  507. {
  508. return WaitAny (tasks, null, token);
  509. }
  510. #endregion
  511. #region Dispose
  512. public void Dispose ()
  513. {
  514. Dispose (true);
  515. }
  516. protected virtual void Dispose (bool disposeManagedRes)
  517. {
  518. // Set action to null so that the GC can collect the delegate and thus
  519. // any big object references that the user might have captured in a anonymous method
  520. if (disposeManagedRes) {
  521. action = null;
  522. completed = null;
  523. state = null;
  524. }
  525. }
  526. #endregion
  527. #region Properties
  528. public static TaskFactory Factory {
  529. get {
  530. return defaultFactory;
  531. }
  532. }
  533. public static int? CurrentId {
  534. get {
  535. Task t = current;
  536. return t == null ? (int?)null : t.Id;
  537. }
  538. }
  539. public AggregateException Exception {
  540. get {
  541. exceptionObserved = true;
  542. return exception;
  543. }
  544. internal set {
  545. exception = value;
  546. }
  547. }
  548. public bool IsCanceled {
  549. get {
  550. return status == TaskStatus.Canceled;
  551. }
  552. }
  553. public bool IsCompleted {
  554. get {
  555. return status == TaskStatus.RanToCompletion ||
  556. status == TaskStatus.Canceled || status == TaskStatus.Faulted;
  557. }
  558. }
  559. public bool IsFaulted {
  560. get {
  561. return status == TaskStatus.Faulted;
  562. }
  563. }
  564. public TaskCreationOptions CreationOptions {
  565. get {
  566. return taskCreationOptions;
  567. }
  568. }
  569. public TaskStatus Status {
  570. get {
  571. return status;
  572. }
  573. internal set {
  574. status = value;
  575. }
  576. }
  577. public object AsyncState {
  578. get {
  579. return state;
  580. }
  581. }
  582. bool IAsyncResult.CompletedSynchronously {
  583. get {
  584. return true;
  585. }
  586. }
  587. WaitHandle IAsyncResult.AsyncWaitHandle {
  588. get {
  589. return null;
  590. }
  591. }
  592. public int Id {
  593. get {
  594. return taskId;
  595. }
  596. }
  597. #endregion
  598. }
  599. }
  600. #endif