TaskContinuation.cs 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. //
  2. // TaskContinuation.cs
  3. //
  4. // Authors:
  5. // Jérémie Laval <jeremie dot laval at xamarin dot com>
  6. // Marek Safar <[email protected]>
  7. //
  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
  30. using System.Collections.Generic;
  31. namespace System.Threading.Tasks
  32. {
  33. interface IContinuation
  34. {
  35. void Execute ();
  36. }
  37. class TaskContinuation : IContinuation
  38. {
  39. readonly Task task;
  40. readonly TaskContinuationOptions continuationOptions;
  41. public TaskContinuation (Task task, TaskContinuationOptions continuationOptions)
  42. {
  43. this.task = task;
  44. this.continuationOptions = continuationOptions;
  45. }
  46. bool ContinuationStatusCheck (TaskContinuationOptions kind)
  47. {
  48. if (kind == TaskContinuationOptions.None)
  49. return true;
  50. int kindCode = (int) kind;
  51. var status = task.ContinuationAncestor.Status;
  52. if (kindCode >= ((int) TaskContinuationOptions.NotOnRanToCompletion)) {
  53. // Remove other options
  54. kind &= ~(TaskContinuationOptions.PreferFairness
  55. | TaskContinuationOptions.LongRunning
  56. | TaskContinuationOptions.AttachedToParent
  57. | TaskContinuationOptions.ExecuteSynchronously);
  58. if (status == TaskStatus.Canceled) {
  59. if (kind == TaskContinuationOptions.NotOnCanceled)
  60. return false;
  61. if (kind == TaskContinuationOptions.OnlyOnFaulted)
  62. return false;
  63. if (kind == TaskContinuationOptions.OnlyOnRanToCompletion)
  64. return false;
  65. } else if (status == TaskStatus.Faulted) {
  66. if (kind == TaskContinuationOptions.NotOnFaulted)
  67. return false;
  68. if (kind == TaskContinuationOptions.OnlyOnCanceled)
  69. return false;
  70. if (kind == TaskContinuationOptions.OnlyOnRanToCompletion)
  71. return false;
  72. } else if (status == TaskStatus.RanToCompletion) {
  73. if (kind == TaskContinuationOptions.NotOnRanToCompletion)
  74. return false;
  75. if (kind == TaskContinuationOptions.OnlyOnFaulted)
  76. return false;
  77. if (kind == TaskContinuationOptions.OnlyOnCanceled)
  78. return false;
  79. }
  80. }
  81. return true;
  82. }
  83. public void Execute ()
  84. {
  85. if (!ContinuationStatusCheck (continuationOptions)) {
  86. task.CancelReal ();
  87. task.Dispose ();
  88. return;
  89. }
  90. // The task may have been canceled externally
  91. if (task.IsCompleted)
  92. return;
  93. if ((continuationOptions & TaskContinuationOptions.ExecuteSynchronously) != 0)
  94. task.RunSynchronouslyCore (task.scheduler);
  95. else
  96. task.Schedule ();
  97. }
  98. }
  99. class ActionContinuation : IContinuation
  100. {
  101. readonly Action action;
  102. public ActionContinuation (Action action)
  103. {
  104. this.action = action;
  105. }
  106. public void Execute ()
  107. {
  108. action ();
  109. }
  110. }
  111. class SynchronizationContextContinuation : IContinuation
  112. {
  113. readonly Action action;
  114. readonly SynchronizationContext ctx;
  115. public SynchronizationContextContinuation (Action action, SynchronizationContext ctx)
  116. {
  117. this.action = action;
  118. this.ctx = ctx;
  119. }
  120. public void Execute ()
  121. {
  122. ctx.Post (l => ((Action) l) (), action);
  123. }
  124. }
  125. sealed class WhenAllContinuation : IContinuation
  126. {
  127. readonly Task owner;
  128. readonly IList<Task> tasks;
  129. int counter;
  130. public WhenAllContinuation (Task owner, IList<Task> tasks)
  131. {
  132. this.owner = owner;
  133. this.counter = tasks.Count;
  134. this.tasks = tasks;
  135. }
  136. public void Execute ()
  137. {
  138. if (Interlocked.Decrement (ref counter) != 0)
  139. return;
  140. owner.Status = TaskStatus.Running;
  141. bool canceled = false;
  142. List<Exception> exceptions = null;
  143. foreach (var task in tasks) {
  144. if (task.IsFaulted) {
  145. if (exceptions == null)
  146. exceptions = new List<Exception> ();
  147. exceptions.AddRange (task.Exception.InnerExceptions);
  148. continue;
  149. }
  150. if (task.IsCanceled) {
  151. canceled = true;
  152. }
  153. }
  154. if (exceptions != null) {
  155. owner.TrySetException (new AggregateException (exceptions));
  156. return;
  157. }
  158. if (canceled) {
  159. owner.CancelReal ();
  160. return;
  161. }
  162. owner.Finish ();
  163. }
  164. }
  165. sealed class WhenAllContinuation<TResult> : IContinuation
  166. {
  167. readonly Task<TResult[]> owner;
  168. readonly IList<Task<TResult>> tasks;
  169. int counter;
  170. public WhenAllContinuation (Task<TResult[]> owner, IList<Task<TResult>> tasks)
  171. {
  172. this.owner = owner;
  173. this.counter = tasks.Count;
  174. this.tasks = tasks;
  175. }
  176. public void Execute ()
  177. {
  178. if (Interlocked.Decrement (ref counter) != 0)
  179. return;
  180. bool canceled = false;
  181. List<Exception> exceptions = null;
  182. TResult[] results = null;
  183. for (int i = 0; i < tasks.Count; ++i) {
  184. var task = tasks [i];
  185. if (task.IsFaulted) {
  186. if (exceptions == null)
  187. exceptions = new List<Exception> ();
  188. exceptions.AddRange (task.Exception.InnerExceptions);
  189. continue;
  190. }
  191. if (task.IsCanceled) {
  192. canceled = true;
  193. continue;
  194. }
  195. if (results == null) {
  196. if (canceled || exceptions != null)
  197. continue;
  198. results = new TResult[tasks.Count];
  199. }
  200. results[i] = task.Result;
  201. }
  202. if (exceptions != null) {
  203. owner.TrySetException (new AggregateException (exceptions));
  204. return;
  205. }
  206. if (canceled) {
  207. owner.CancelReal ();
  208. return;
  209. }
  210. owner.TrySetResult (results);
  211. }
  212. }
  213. sealed class WhenAnyContinuation<T> : IContinuation where T : Task
  214. {
  215. readonly Task<T> owner;
  216. readonly IList<T> tasks;
  217. AtomicBooleanValue executed = new AtomicBooleanValue ();
  218. public WhenAnyContinuation (Task<T> owner, IList<T> tasks)
  219. {
  220. this.owner = owner;
  221. this.tasks = tasks;
  222. }
  223. public void Execute ()
  224. {
  225. if (!executed.TryRelaxedSet ())
  226. return;
  227. for (int i = 0; i < tasks.Count; ++i) {
  228. var task = tasks[i];
  229. if (!task.IsCompleted)
  230. continue;
  231. owner.TrySetResult (task);
  232. return;
  233. }
  234. }
  235. }
  236. sealed class ManualResetContinuation : IContinuation, IDisposable
  237. {
  238. readonly ManualResetEventSlim evt;
  239. public ManualResetContinuation ()
  240. {
  241. this.evt = new ManualResetEventSlim ();
  242. }
  243. public ManualResetEventSlim Event {
  244. get {
  245. return evt;
  246. }
  247. }
  248. public void Dispose ()
  249. {
  250. evt.Dispose ();
  251. }
  252. public void Execute ()
  253. {
  254. evt.Set ();
  255. }
  256. }
  257. sealed class CountdownContinuation : IContinuation, IDisposable
  258. {
  259. readonly CountdownEvent evt;
  260. public CountdownContinuation (int initialCount)
  261. {
  262. this.evt = new CountdownEvent (initialCount);
  263. }
  264. public CountdownEvent Event {
  265. get {
  266. return evt;
  267. }
  268. }
  269. public void Dispose ()
  270. {
  271. evt.Dispose ();
  272. }
  273. public void Execute ()
  274. {
  275. evt.Signal ();
  276. }
  277. }
  278. }
  279. #endif