Task.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720
  1. #if NET_4_0
  2. // Task.cs
  3. //
  4. // Copyright (c) 2008 Jérémie "Garuma" Laval
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. // THE SOFTWARE.
  23. //
  24. //
  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) => 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 {
  193. if (!predicate ()) return;
  194. if (!launched.Value && !launched.Exchange (true)) {
  195. if (!ContinuationStatusCheck (kind)) {
  196. continuation.CancelReal ();
  197. continuation.Dispose ();
  198. return;
  199. }
  200. CheckAndSchedule (continuation, kind, scheduler);
  201. }
  202. };
  203. if (IsCompleted) {
  204. action (this, 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 (this, 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)
  244. {
  245. if (options == TaskContinuationOptions.None || (options & TaskContinuationOptions.ExecuteSynchronously) > 0)
  246. continuation.ThreadStart ();
  247. else
  248. continuation.Start (scheduler);
  249. }
  250. internal TaskCreationOptions GetCreationOptions (TaskContinuationOptions kind)
  251. {
  252. TaskCreationOptions options = TaskCreationOptions.None;
  253. if ((kind & TaskContinuationOptions.AttachedToParent) > 0)
  254. options |= TaskCreationOptions.AttachedToParent;
  255. if ((kind & TaskContinuationOptions.PreferFairness) > 0)
  256. options |= TaskCreationOptions.PreferFairness;
  257. if ((kind & TaskContinuationOptions.LongRunning) > 0)
  258. options |= TaskCreationOptions.LongRunning;
  259. return options;
  260. }
  261. #endregion
  262. #region Internal and protected thingies
  263. internal void Schedule ()
  264. {
  265. status = TaskStatus.WaitingToRun;
  266. // If worker is null it means it is a local one, revert to the old behavior
  267. if (childWorkAdder == null || CheckTaskOptions (taskCreationOptions, TaskCreationOptions.PreferFairness)) {
  268. scheduler.AddWork (this);
  269. } else {
  270. /* Like the semantic of the ABP paper describe it, we add ourselves to the bottom
  271. * of our Parent Task's ThreadWorker deque. It's ok to do that since we are in
  272. * the correct Thread during the creation
  273. */
  274. childWorkAdder (this);
  275. }
  276. }
  277. void ThreadStart ()
  278. {
  279. current = this;
  280. TaskScheduler.Current = taskScheduler;
  281. if (!token.IsCancellationRequested) {
  282. status = TaskStatus.Running;
  283. try {
  284. InnerInvoke ();
  285. } catch (Exception e) {
  286. exception = new AggregateException (e);
  287. status = TaskStatus.Faulted;
  288. if (taskScheduler.FireUnobservedEvent (Exception).Observed)
  289. exceptionObserved = true;
  290. }
  291. } else {
  292. CancelReal ();
  293. }
  294. Finish ();
  295. }
  296. internal void Execute (Action<Task> childAdder)
  297. {
  298. childWorkAdder = childAdder;
  299. ThreadStart ();
  300. }
  301. internal void AddChild ()
  302. {
  303. childTasks.AddCount ();
  304. }
  305. internal void ChildCompleted ()
  306. {
  307. childTasks.Signal ();
  308. if (childTasks.IsSet && status == TaskStatus.WaitingForChildrenToComplete)
  309. status = TaskStatus.RanToCompletion;
  310. }
  311. internal virtual void InnerInvoke ()
  312. {
  313. if (action != null)
  314. action (state);
  315. // Set action to null so that the GC can collect the delegate and thus
  316. // any big object references that the user might have captured in an anonymous method
  317. action = null;
  318. state = null;
  319. }
  320. internal void Finish ()
  321. {
  322. // If there wasn't any child created in the task we set the CountdownEvent
  323. childTasks.Signal ();
  324. // Don't override Canceled or Faulted
  325. if (status == TaskStatus.Running) {
  326. if (childTasks.IsSet )
  327. status = TaskStatus.RanToCompletion;
  328. else
  329. status = TaskStatus.WaitingForChildrenToComplete;
  330. }
  331. // Call the event in the correct style
  332. EventHandler tempCompleted = completed;
  333. if (tempCompleted != null)
  334. tempCompleted (this, EventArgs.Empty);
  335. // Reset the current thingies
  336. current = null;
  337. TaskScheduler.Current = null;
  338. // Tell parent that we are finished
  339. if (CheckTaskOptions (taskCreationOptions, TaskCreationOptions.AttachedToParent) && parent != null){
  340. parent.ChildCompleted ();
  341. }
  342. Dispose ();
  343. }
  344. #endregion
  345. #region Cancel and Wait related method
  346. internal void CancelReal ()
  347. {
  348. exception = new AggregateException (new TaskCanceledException (this));
  349. status = TaskStatus.Canceled;
  350. }
  351. public void Wait ()
  352. {
  353. if (scheduler == null)
  354. throw new InvalidOperationException ("The Task hasn't been Started and thus can't be waited on");
  355. scheduler.ParticipateUntil (this);
  356. if (exception != null)
  357. throw exception;
  358. }
  359. public void Wait (CancellationToken token)
  360. {
  361. Wait (null, token);
  362. }
  363. public bool Wait (TimeSpan ts)
  364. {
  365. return Wait ((int)ts.TotalMilliseconds, CancellationToken.None);
  366. }
  367. public bool Wait (int millisecondsTimeout)
  368. {
  369. return Wait (millisecondsTimeout, CancellationToken.None);
  370. }
  371. public bool Wait (int millisecondsTimeout, CancellationToken token)
  372. {
  373. Watch sw = Watch.StartNew ();
  374. return Wait (() => sw.ElapsedMilliseconds >= millisecondsTimeout, token);
  375. }
  376. bool Wait (Func<bool> stopFunc, CancellationToken token)
  377. {
  378. if (scheduler == null)
  379. throw new InvalidOperationException ("The Task hasn't been Started and thus can't be waited on");
  380. bool result = scheduler.ParticipateUntil (this, delegate {
  381. if (token.IsCancellationRequested)
  382. throw new OperationCanceledException ("The CancellationToken has had cancellation requested.");
  383. return (stopFunc != null) ? stopFunc () : false;
  384. });
  385. if (exception != null)
  386. throw exception;
  387. return !result;
  388. }
  389. public static void WaitAll (params Task[] tasks)
  390. {
  391. if (tasks == null)
  392. throw new ArgumentNullException ("tasks");
  393. if (tasks.Length == 0)
  394. throw new ArgumentException ("tasks is empty", "tasks");
  395. foreach (var t in tasks)
  396. t.Wait ();
  397. }
  398. public static void WaitAll (Task[] tasks, CancellationToken token)
  399. {
  400. if (tasks == null)
  401. throw new ArgumentNullException ("tasks");
  402. if (tasks.Length == 0)
  403. throw new ArgumentException ("tasks is empty", "tasks");
  404. foreach (var t in tasks)
  405. t.Wait (token);
  406. }
  407. public static bool WaitAll (Task[] tasks, TimeSpan ts)
  408. {
  409. if (tasks == null)
  410. throw new ArgumentNullException ("tasks");
  411. if (tasks.Length == 0)
  412. throw new ArgumentException ("tasks is empty", "tasks");
  413. bool result = true;
  414. foreach (var t in tasks)
  415. result &= t.Wait (ts);
  416. return result;
  417. }
  418. public static bool WaitAll (Task[] tasks, int millisecondsTimeout)
  419. {
  420. if (tasks == null)
  421. throw new ArgumentNullException ("tasks");
  422. if (tasks.Length == 0)
  423. throw new ArgumentException ("tasks is empty", "tasks");
  424. bool result = true;
  425. foreach (var t in tasks)
  426. result &= t.Wait (millisecondsTimeout);
  427. return result;
  428. }
  429. public static bool WaitAll (Task[] tasks, int millisecondsTimeout, CancellationToken token)
  430. {
  431. if (tasks == null)
  432. throw new ArgumentNullException ("tasks");
  433. if (tasks.Length == 0)
  434. throw new ArgumentException ("tasks is empty", "tasks");
  435. bool result = true;
  436. foreach (var t in tasks)
  437. result &= t.Wait (millisecondsTimeout, token);
  438. return result;
  439. }
  440. public static int WaitAny (params Task[] tasks)
  441. {
  442. return WaitAny (tasks, null, null);
  443. }
  444. static int WaitAny (Task[] tasks, Func<bool> stopFunc, CancellationToken? token)
  445. {
  446. if (tasks == null)
  447. throw new ArgumentNullException ("tasks");
  448. if (tasks.Length == 0)
  449. throw new ArgumentException ("tasks is empty", "tasks");
  450. int numFinished = 0;
  451. int indexFirstFinished = -1;
  452. int index = 0;
  453. foreach (Task t in tasks) {
  454. t.ContinueWith (delegate {
  455. int indexResult = index;
  456. int result = Interlocked.Increment (ref numFinished);
  457. // Check if we are the first to have finished
  458. if (result == 1)
  459. indexFirstFinished = indexResult;
  460. });
  461. index++;
  462. }
  463. // One task already finished
  464. if (indexFirstFinished != -1)
  465. return indexFirstFinished;
  466. // All tasks are supposed to use the same TaskManager
  467. tasks[0].scheduler.ParticipateUntil (delegate {
  468. if (stopFunc != null && stopFunc ())
  469. return true;
  470. if (token.HasValue && token.Value.IsCancellationRequested)
  471. throw new OperationCanceledException ("The CancellationToken has had cancellation requested.");
  472. return numFinished >= 1;
  473. });
  474. return indexFirstFinished;
  475. }
  476. public static int WaitAny (Task[] tasks, TimeSpan ts)
  477. {
  478. return WaitAny (tasks, (int)ts.TotalMilliseconds);
  479. }
  480. public static int WaitAny (Task[] tasks, int millisecondsTimeout)
  481. {
  482. if (millisecondsTimeout < -1)
  483. throw new ArgumentOutOfRangeException ("millisecondsTimeout");
  484. if (millisecondsTimeout == -1)
  485. return WaitAny (tasks);
  486. Watch sw = Watch.StartNew ();
  487. return WaitAny (tasks, () => sw.ElapsedMilliseconds > millisecondsTimeout, null);
  488. }
  489. public static int WaitAny (Task[] tasks, int millisecondsTimeout, CancellationToken token)
  490. {
  491. if (millisecondsTimeout < -1)
  492. throw new ArgumentOutOfRangeException ("millisecondsTimeout");
  493. if (millisecondsTimeout == -1)
  494. return WaitAny (tasks);
  495. Watch sw = Watch.StartNew ();
  496. return WaitAny (tasks, () => sw.ElapsedMilliseconds > millisecondsTimeout, token);
  497. }
  498. public static int WaitAny (Task[] tasks, CancellationToken token)
  499. {
  500. return WaitAny (tasks, null, token);
  501. }
  502. #endregion
  503. #region Dispose
  504. public void Dispose ()
  505. {
  506. Dispose (true);
  507. }
  508. protected virtual void Dispose (bool disposeManagedRes)
  509. {
  510. // Set action to null so that the GC can collect the delegate and thus
  511. // any big object references that the user might have captured in a anonymous method
  512. if (disposeManagedRes) {
  513. action = null;
  514. completed = null;
  515. state = null;
  516. }
  517. }
  518. #endregion
  519. #region Properties
  520. public static TaskFactory Factory {
  521. get {
  522. return defaultFactory;
  523. }
  524. }
  525. public static int? CurrentId {
  526. get {
  527. Task t = current;
  528. return t == null ? (int?)null : t.Id;
  529. }
  530. }
  531. public AggregateException Exception {
  532. get {
  533. exceptionObserved = true;
  534. return exception;
  535. }
  536. internal set {
  537. exception = value;
  538. }
  539. }
  540. public bool IsCanceled {
  541. get {
  542. return status == TaskStatus.Canceled;
  543. }
  544. }
  545. public bool IsCompleted {
  546. get {
  547. return status == TaskStatus.RanToCompletion ||
  548. status == TaskStatus.Canceled || status == TaskStatus.Faulted;
  549. }
  550. }
  551. public bool IsFaulted {
  552. get {
  553. return status == TaskStatus.Faulted;
  554. }
  555. }
  556. public TaskCreationOptions CreationOptions {
  557. get {
  558. return taskCreationOptions;
  559. }
  560. }
  561. public TaskStatus Status {
  562. get {
  563. return status;
  564. }
  565. internal set {
  566. status = value;
  567. }
  568. }
  569. public object AsyncState {
  570. get {
  571. return state;
  572. }
  573. }
  574. bool IAsyncResult.CompletedSynchronously {
  575. get {
  576. return true;
  577. }
  578. }
  579. WaitHandle IAsyncResult.AsyncWaitHandle {
  580. get {
  581. return null;
  582. }
  583. }
  584. public int Id {
  585. get {
  586. return taskId;
  587. }
  588. }
  589. #endregion
  590. }
  591. }
  592. #endif