TaskFactoryTest.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. //
  2. // TaskFactoryTest.cs
  3. //
  4. // Authors:
  5. // Jérémie "Garuma" Laval <[email protected]>
  6. // Marek Safar <[email protected]>
  7. //
  8. // Copyright (c) 2010 Jérémie "Garuma" Laval
  9. // Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
  10. //
  11. // Permission is hereby granted, free of charge, to any person obtaining a copy
  12. // of this software and associated documentation files (the "Software"), to deal
  13. // in the Software without restriction, including without limitation the rights
  14. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  15. // copies of the Software, and to permit persons to whom the Software is
  16. // furnished to do so, subject to the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be included in
  19. // all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  22. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  23. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  24. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  25. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  26. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  27. // THE SOFTWARE.
  28. //
  29. //
  30. #if NET_4_0 || MOBILE
  31. using System;
  32. using System.Threading;
  33. using System.Threading.Tasks;
  34. using System.Collections.Generic;
  35. using NUnit.Framework;
  36. namespace MonoTests.System.Threading.Tasks
  37. {
  38. [TestFixture]
  39. public class TaskFactoryTests
  40. {
  41. class CompletedAsyncResult : IAsyncResult
  42. {
  43. public object AsyncState
  44. {
  45. get { throw new NotImplementedException (); }
  46. }
  47. public WaitHandle AsyncWaitHandle
  48. {
  49. get { throw new NotImplementedException (); }
  50. }
  51. public bool CompletedSynchronously
  52. {
  53. get { throw new NotImplementedException (); }
  54. }
  55. public bool IsCompleted
  56. {
  57. get { return true; }
  58. }
  59. }
  60. class TestAsyncResult : IAsyncResult
  61. {
  62. WaitHandle wh = new ManualResetEvent (true);
  63. public object AsyncState
  64. {
  65. get { throw new NotImplementedException (); }
  66. }
  67. public WaitHandle AsyncWaitHandle
  68. {
  69. get
  70. {
  71. return wh;
  72. }
  73. }
  74. public bool CompletedSynchronously
  75. {
  76. get { throw new NotImplementedException (); }
  77. }
  78. public bool IsCompleted
  79. {
  80. get { return false; }
  81. }
  82. }
  83. class TestScheduler : TaskScheduler
  84. {
  85. public bool ExecutedInline { get; set; }
  86. protected override void QueueTask (Task task)
  87. {
  88. throw new NotImplementedException ();
  89. }
  90. protected override bool TryDequeue (Task task)
  91. {
  92. throw new NotImplementedException ();
  93. }
  94. protected override bool TryExecuteTaskInline (Task task, bool taskWasPreviouslyQueued)
  95. {
  96. if (taskWasPreviouslyQueued)
  97. throw new ArgumentException ("taskWasPreviouslyQueued");
  98. if (task.Status != TaskStatus.WaitingToRun)
  99. throw new ArgumentException ("task.Status");
  100. ExecutedInline = true;
  101. return TryExecuteTask (task);
  102. }
  103. protected override IEnumerable<Task> GetScheduledTasks ()
  104. {
  105. throw new NotImplementedException ();
  106. }
  107. }
  108. TaskFactory factory;
  109. [SetUp]
  110. public void Setup ()
  111. {
  112. this.factory = Task.Factory;
  113. }
  114. [Test]
  115. public void StartNewTest ()
  116. {
  117. bool result = false;
  118. factory.StartNew (() => result = true).Wait ();
  119. Assert.IsTrue (result);
  120. }
  121. [Test]
  122. public void NoDefaultScheduler ()
  123. {
  124. Assert.IsNull (factory.Scheduler, "#1");
  125. }
  126. [Test]
  127. public void ContinueWhenAllTest ()
  128. {
  129. bool r1 = false, r2 = false, r3 = false;
  130. Task[] tasks = new Task[3];
  131. tasks[0] = new Task (() => { Thread.Sleep (100); r1 = true; });
  132. tasks[1] = new Task (() => { Thread.Sleep (500); r2 = true; });
  133. tasks[2] = new Task (() => { Thread.Sleep (300); r3 = true; });
  134. bool result = false;
  135. Task cont = factory.ContinueWhenAll (tasks, (ts) => { if (r1 && r2 && r3) result = true; });
  136. foreach (Task t in tasks)
  137. t.Start ();
  138. Assert.IsTrue (cont.Wait (1000), "#0");
  139. Assert.IsTrue (r1, "#1");
  140. Assert.IsTrue (r2, "#2");
  141. Assert.IsTrue (r3, "#3");
  142. Assert.IsTrue (result, "#4");
  143. }
  144. [Test]
  145. public void ContinueWhenAnyTest ()
  146. {
  147. bool r = false, result = false, finished = false;
  148. Task[] tasks = new Task[2];
  149. tasks[0] = new Task (() => { Thread.Sleep (300); r = true; });
  150. tasks[1] = new Task (() => { SpinWait sw = new SpinWait (); while (!finished) sw.SpinOnce (); });
  151. //tasks[2] = new Task (() => { SpinWait sw; while (!finished) sw.SpinOnce (); });
  152. Task cont = factory.ContinueWhenAny (tasks, (t) => { if (r) result = t == tasks[0]; finished = true; });
  153. foreach (Task t in tasks)
  154. t.Start ();
  155. cont.Wait ();
  156. Assert.IsTrue (r, "#1");
  157. Assert.IsTrue (result, "#2");
  158. Assert.IsTrue (finished, "#3");
  159. }
  160. [Test]
  161. public void FromAsyncBeginInvoke_WithResult ()
  162. {
  163. bool result = false;
  164. Func<int, int> func = (i) => {
  165. Assert.IsTrue (Thread.CurrentThread.IsThreadPoolThread);
  166. result = true; return i + 3;
  167. };
  168. var task = factory.FromAsync<int, int> (func.BeginInvoke, func.EndInvoke, 1, "state", TaskCreationOptions.AttachedToParent);
  169. Assert.IsTrue (task.Wait (5000), "#1");
  170. Assert.IsTrue (result, "#2");
  171. Assert.AreEqual (4, task.Result, "#3");
  172. Assert.AreEqual ("state", (string) task.AsyncState, "#4");
  173. Assert.AreEqual (TaskCreationOptions.AttachedToParent, task.CreationOptions, "#5");
  174. }
  175. [Test]
  176. public void FromAsyncBeginMethod_DirectResult ()
  177. {
  178. bool result = false;
  179. bool continuationTest = false;
  180. Func<int, int> func = (i) => { result = true; return i + 3; };
  181. Task<int> task = factory.FromAsync<int> (func.BeginInvoke (1, delegate { }, null), func.EndInvoke);
  182. var cont = task.ContinueWith (_ => continuationTest = true, TaskContinuationOptions.ExecuteSynchronously);
  183. task.Wait ();
  184. cont.Wait ();
  185. Assert.IsTrue (result);
  186. Assert.IsTrue (continuationTest);
  187. Assert.AreEqual (4, task.Result);
  188. }
  189. [Test]
  190. public void FromAsyncBeginMethod_Exception ()
  191. {
  192. bool result = false;
  193. bool continuationTest = false;
  194. Func<int, int> func = (i) => { result = true; throw new ApplicationException ("bleh"); return i + 3; };
  195. Task<int> task = factory.FromAsync<int, int> (func.BeginInvoke, func.EndInvoke, 1, null);
  196. var cont = task.ContinueWith (_ => continuationTest = true, TaskContinuationOptions.ExecuteSynchronously);
  197. try {
  198. task.Wait ();
  199. } catch { }
  200. cont.Wait ();
  201. Assert.IsTrue (result);
  202. Assert.IsTrue (continuationTest);
  203. Assert.IsNotNull (task.Exception);
  204. var agg = task.Exception;
  205. Assert.AreEqual (1, agg.InnerExceptions.Count);
  206. Assert.IsInstanceOfType (typeof (ApplicationException), agg.InnerExceptions[0]);
  207. Assert.AreEqual (TaskStatus.Faulted, task.Status);
  208. try {
  209. var a = task.Result;
  210. Assert.Fail ();
  211. } catch (AggregateException) {
  212. }
  213. }
  214. [Test]
  215. public void FromAsync_ArgumentsCheck ()
  216. {
  217. var result = new CompletedAsyncResult ();
  218. try {
  219. factory.FromAsync (null, l => { });
  220. Assert.Fail ("#1");
  221. } catch (ArgumentNullException) {
  222. }
  223. try {
  224. factory.FromAsync (result, null);
  225. Assert.Fail ("#2");
  226. } catch (ArgumentNullException) {
  227. }
  228. try {
  229. factory.FromAsync (result, l => { }, TaskCreationOptions.LongRunning);
  230. Assert.Fail ("#3");
  231. } catch (ArgumentOutOfRangeException) {
  232. }
  233. try {
  234. factory.FromAsync (result, l => { }, TaskCreationOptions.PreferFairness);
  235. Assert.Fail ("#4");
  236. } catch (ArgumentOutOfRangeException) {
  237. }
  238. try {
  239. factory.FromAsync (result, l => { }, TaskCreationOptions.None, null);
  240. Assert.Fail ("#5");
  241. } catch (ArgumentNullException) {
  242. }
  243. try {
  244. factory.FromAsync (null, l => { }, null, TaskCreationOptions.None);
  245. Assert.Fail ("#6");
  246. } catch (ArgumentNullException) {
  247. }
  248. try {
  249. factory.FromAsync ((a, b) => null, l => { }, null, TaskCreationOptions.LongRunning);
  250. Assert.Fail ("#7");
  251. } catch (ArgumentOutOfRangeException) {
  252. }
  253. }
  254. [Test]
  255. public void FromAsync_Completed ()
  256. {
  257. var completed = new CompletedAsyncResult ();
  258. bool? valid = null;
  259. Action<IAsyncResult> end = l => {
  260. Assert.IsFalse (Thread.CurrentThread.IsThreadPoolThread, "#2");
  261. valid = l == completed;
  262. };
  263. Task task = factory.FromAsync (completed, end);
  264. Assert.IsTrue (valid == true, "#1");
  265. }
  266. [Test]
  267. public void FromAsync_CompletedWithException ()
  268. {
  269. var completed = new CompletedAsyncResult ();
  270. Action<IAsyncResult> end = l => {
  271. throw new ApplicationException ();
  272. };
  273. Task task = factory.FromAsync (completed, end);
  274. Assert.AreEqual (TaskStatus.Faulted, task.Status, "#1");
  275. }
  276. [Test]
  277. public void FromAsync_CompletedCanceled ()
  278. {
  279. var completed = new CompletedAsyncResult ();
  280. Action<IAsyncResult> end = l => {
  281. throw new OperationCanceledException ();
  282. };
  283. Task task = factory.FromAsync (completed, end);
  284. Assert.AreEqual (TaskStatus.Canceled, task.Status, "#1");
  285. Assert.IsNull (task.Exception, "#2");
  286. }
  287. [Test]
  288. public void FromAsync_SimpleAsyncResult ()
  289. {
  290. var result = new TestAsyncResult ();
  291. bool called = false;
  292. var task = factory.FromAsync (result, l => {
  293. called = true;
  294. });
  295. Assert.IsTrue (task.Wait (1000), "#1");
  296. Assert.IsTrue (called, "#2");
  297. }
  298. [Test]
  299. public void FromAsync_ResultException ()
  300. {
  301. var result = new TestAsyncResult ();
  302. var task = factory.FromAsync (result, l => {
  303. throw new ApplicationException ();
  304. });
  305. try {
  306. Assert.IsFalse (task.Wait (1000), "#1");
  307. } catch (AggregateException) {
  308. }
  309. Assert.AreEqual (TaskStatus.Faulted, task.Status, "#2");
  310. }
  311. [Test]
  312. public void FromAsync_ReturnInt ()
  313. {
  314. var result = new TestAsyncResult ();
  315. bool called = false;
  316. var task = factory.FromAsync<int> (result, l => {
  317. called = true;
  318. return 4;
  319. });
  320. Assert.IsTrue (task.Wait (1000), "#1");
  321. Assert.IsTrue (called, "#2");
  322. Assert.AreEqual (4, task.Result, "#3");
  323. }
  324. [Test]
  325. public void FromAsync_Scheduler_Explicit ()
  326. {
  327. var result = new TestAsyncResult ();
  328. bool called = false;
  329. var scheduler = new TestScheduler ();
  330. var task = factory.FromAsync (result, l => {
  331. called = true;
  332. }, TaskCreationOptions.None, scheduler);
  333. Assert.IsTrue (task.Wait (5000), "#1");
  334. Assert.IsTrue (called, "#2");
  335. Assert.IsTrue (scheduler.ExecutedInline, "#3");
  336. }
  337. [Test]
  338. public void FromAsync_Scheduler_Implicit ()
  339. {
  340. var result = new TestAsyncResult ();
  341. bool called = false;
  342. var scheduler = new TestScheduler ();
  343. factory = new TaskFactory (scheduler);
  344. Task task = factory.FromAsync (result, l => {
  345. Assert.IsTrue (Thread.CurrentThread.IsThreadPoolThread, "#6");
  346. called = true;
  347. }, TaskCreationOptions.AttachedToParent);
  348. Assert.AreEqual (TaskCreationOptions.AttachedToParent, task.CreationOptions, "#1");
  349. Assert.IsNull (task.AsyncState, "#2");
  350. Assert.IsTrue (task.Wait (5000), "#3");
  351. Assert.IsTrue (called, "#4");
  352. Assert.IsTrue (scheduler.ExecutedInline, "#5");
  353. }
  354. [Test]
  355. public void FromAsync_BeginCallback ()
  356. {
  357. bool called = false;
  358. bool called2 = false;
  359. var task = factory.FromAsync (
  360. (a, b, c) => {
  361. if (a != "h")
  362. Assert.Fail ("#10");
  363. if ((TaskCreationOptions) c != TaskCreationOptions.AttachedToParent)
  364. Assert.Fail ("#11");
  365. Assert.IsFalse (Thread.CurrentThread.IsThreadPoolThread, "#12");
  366. called2 = true;
  367. b.Invoke (null);
  368. return null;
  369. },
  370. l => {
  371. called = true;
  372. },
  373. "h", TaskCreationOptions.AttachedToParent);
  374. Assert.AreEqual (TaskCreationOptions.None, task.CreationOptions, "#1");
  375. Assert.AreEqual (TaskCreationOptions.AttachedToParent, (TaskCreationOptions) task.AsyncState, "#2");
  376. Assert.IsTrue (task.Wait (5000), "#3");
  377. Assert.IsTrue (called, "#4");
  378. Assert.IsTrue (called2, "#5");
  379. }
  380. }
  381. }
  382. #endif