TaskFactoryTest.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  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. #if !MOBILE
  37. using NUnit.Framework.SyntaxHelpers;
  38. #endif
  39. namespace MonoTests.System.Threading.Tasks
  40. {
  41. [TestFixture]
  42. public class TaskFactoryTests
  43. {
  44. class CompletedAsyncResult : IAsyncResult
  45. {
  46. public object AsyncState
  47. {
  48. get { throw new NotImplementedException (); }
  49. }
  50. public WaitHandle AsyncWaitHandle
  51. {
  52. get { throw new NotImplementedException (); }
  53. }
  54. public bool CompletedSynchronously
  55. {
  56. get { throw new NotImplementedException (); }
  57. }
  58. public bool IsCompleted
  59. {
  60. get { return true; }
  61. }
  62. }
  63. class TestAsyncResult : IAsyncResult
  64. {
  65. WaitHandle wh = new ManualResetEvent (true);
  66. public object AsyncState
  67. {
  68. get { throw new NotImplementedException (); }
  69. }
  70. public WaitHandle AsyncWaitHandle
  71. {
  72. get
  73. {
  74. return wh;
  75. }
  76. }
  77. public bool CompletedSynchronously
  78. {
  79. get { throw new NotImplementedException (); }
  80. }
  81. public bool IsCompleted
  82. {
  83. get { return false; }
  84. }
  85. }
  86. class TestScheduler : TaskScheduler
  87. {
  88. public bool ExecutedInline { get; set; }
  89. protected override void QueueTask (Task task)
  90. {
  91. throw new NotImplementedException ();
  92. }
  93. protected override bool TryDequeue (Task task)
  94. {
  95. throw new NotImplementedException ();
  96. }
  97. protected override bool TryExecuteTaskInline (Task task, bool taskWasPreviouslyQueued)
  98. {
  99. if (taskWasPreviouslyQueued)
  100. throw new ArgumentException ("taskWasPreviouslyQueued");
  101. if (task.Status != TaskStatus.WaitingToRun)
  102. throw new ArgumentException ("task.Status");
  103. ExecutedInline = true;
  104. return TryExecuteTask (task);
  105. }
  106. protected override IEnumerable<Task> GetScheduledTasks ()
  107. {
  108. throw new NotImplementedException ();
  109. }
  110. }
  111. TaskFactory factory;
  112. [SetUp]
  113. public void Setup ()
  114. {
  115. this.factory = Task.Factory;
  116. }
  117. [Test]
  118. public void StartNewTest ()
  119. {
  120. bool result = false;
  121. factory.StartNew (() => result = true).Wait ();
  122. Assert.IsTrue (result);
  123. }
  124. [Test]
  125. public void NoDefaultScheduler ()
  126. {
  127. Assert.IsNull (factory.Scheduler, "#1");
  128. }
  129. [Test]
  130. public void ContinueWhenAll_Simple ()
  131. {
  132. var mre = new ManualResetEventSlim (false);
  133. Task[] tasks = new Task[3];
  134. tasks[0] = new Task (() => { Thread.Sleep (0); Assert.IsTrue (mre.Wait (3000)); });
  135. tasks[1] = new Task (() => { Assert.IsTrue (mre.Wait (3000)); });
  136. tasks[2] = new Task (() => { Assert.IsTrue (mre.Wait (3000)); });
  137. bool ran = false;
  138. Task cont = factory.ContinueWhenAll (tasks, ts => {
  139. Assert.AreEqual (tasks, ts, "#0");
  140. ran = true;
  141. });
  142. foreach (Task t in tasks)
  143. t.Start ();
  144. mre.Set ();
  145. Assert.IsTrue (cont.Wait (1000), "#1");
  146. Assert.IsTrue (ran, "#2");
  147. }
  148. [Test]
  149. public void ContinueWhenAll_WithMixedCompletionState ()
  150. {
  151. var mre = new ManualResetEventSlim ();
  152. var task = Task.Factory.StartNew (() => mre.Wait (200));
  153. var contFailed = task.ContinueWith (t => {}, TaskContinuationOptions.OnlyOnFaulted);
  154. var contCanceled = task.ContinueWith (t => {}, TaskContinuationOptions.OnlyOnCanceled);
  155. var contSuccess = task.ContinueWith (t => {}, TaskContinuationOptions.OnlyOnRanToCompletion);
  156. bool ran = false;
  157. var cont = Task.Factory.ContinueWhenAll (new Task[] { contFailed, contCanceled, contSuccess }, _ => ran = true);
  158. mre.Set ();
  159. cont.Wait (200);
  160. Assert.IsTrue (ran);
  161. Assert.AreEqual (TaskStatus.RanToCompletion, cont.Status);
  162. }
  163. [Test]
  164. public void ContinueWhenAll_InvalidArguments ()
  165. {
  166. try {
  167. factory.ContinueWhenAll (null, delegate { });
  168. Assert.Fail ("#1");
  169. } catch (ArgumentNullException) {
  170. }
  171. try {
  172. factory.ContinueWhenAll (new Task[0], delegate { });
  173. Assert.Fail ("#2");
  174. } catch (ArgumentException) {
  175. }
  176. try {
  177. factory.ContinueWhenAll (new Task[] { null }, delegate { });
  178. Assert.Fail ("#3");
  179. } catch (ArgumentException) {
  180. }
  181. var tasks = new Task [] {
  182. factory.StartNew (delegate {})
  183. };
  184. try {
  185. factory.ContinueWhenAll (tasks, null);
  186. Assert.Fail ("#4");
  187. } catch (ArgumentException) {
  188. }
  189. try {
  190. factory.ContinueWhenAll (tasks, delegate { }, CancellationToken.None, TaskContinuationOptions.None, null);
  191. Assert.Fail ("#5");
  192. } catch (ArgumentException) {
  193. }
  194. try {
  195. factory.ContinueWhenAll (tasks, delegate { }, CancellationToken.None, TaskContinuationOptions.OnlyOnCanceled, null);
  196. Assert.Fail ("#6");
  197. } catch (ArgumentException) {
  198. }
  199. }
  200. [Test]
  201. public void ContinueWhenAll_WithExceptions ()
  202. {
  203. var t1 = Task.Factory.StartNew (() => { throw new ApplicationException ("Foo"); });
  204. var t2 = Task.Factory.StartNew (() => { throw new ApplicationException ("Bar"); });
  205. var cont = Task.Factory.ContinueWhenAll (new[] { t1, t2 }, delegate {});
  206. cont.Wait (200);
  207. Assert.IsTrue (t1.IsFaulted);
  208. Assert.IsTrue (t2.IsFaulted);
  209. Assert.AreEqual (TaskStatus.RanToCompletion, cont.Status);
  210. }
  211. [Test]
  212. public void ContinueWhenAny_Simple ()
  213. {
  214. var t1 = new ManualResetEvent (false);
  215. var t2 = new ManualResetEvent (false);
  216. var tasks = new Task[2] {
  217. Task.Factory.StartNew (() => { t1.WaitOne (3000); }),
  218. Task.Factory.StartNew (() => { t2.WaitOne (3000); })
  219. };
  220. bool ran = false;
  221. var ct = new CancellationToken ();
  222. Task cont = factory.ContinueWhenAny (tasks, t => {
  223. Assert.AreEqual (tasks[0], t, "#1");
  224. ran = true;
  225. }, ct);
  226. Assert.AreEqual (TaskStatus.WaitingForActivation, cont.Status, "#2");
  227. t1.Set ();
  228. Assert.IsTrue (cont.Wait (2000), "#10");
  229. Assert.IsTrue (ran, "#11");
  230. t2.Set ();
  231. }
  232. [Test]
  233. public void ContinueWhenAny_InvalidArguments ()
  234. {
  235. try {
  236. factory.ContinueWhenAny (null, delegate { });
  237. Assert.Fail ("#1");
  238. } catch (ArgumentNullException) {
  239. }
  240. try {
  241. factory.ContinueWhenAny (new Task[0], delegate { });
  242. Assert.Fail ("#2");
  243. } catch (ArgumentException) {
  244. }
  245. try {
  246. factory.ContinueWhenAny (new Task[] { null }, delegate { });
  247. Assert.Fail ("#3");
  248. } catch (ArgumentException) {
  249. }
  250. var tasks = new Task [] {
  251. factory.StartNew (delegate {})
  252. };
  253. try {
  254. factory.ContinueWhenAny (tasks, null);
  255. Assert.Fail ("#4");
  256. } catch (ArgumentException) {
  257. }
  258. try {
  259. factory.ContinueWhenAny (tasks, delegate { }, CancellationToken.None, TaskContinuationOptions.None, null);
  260. Assert.Fail ("#5");
  261. } catch (ArgumentException) {
  262. }
  263. try {
  264. factory.ContinueWhenAny (tasks, delegate { }, CancellationToken.None, TaskContinuationOptions.OnlyOnCanceled, null);
  265. Assert.Fail ("#6");
  266. } catch (ArgumentException) {
  267. }
  268. }
  269. [Test]
  270. public void FromAsyncBeginInvoke_WithResult ()
  271. {
  272. bool result = false;
  273. Func<int, int> func = (i) => {
  274. Assert.IsTrue (Thread.CurrentThread.IsThreadPoolThread);
  275. result = true; return i + 3;
  276. };
  277. var task = factory.FromAsync<int, int> (func.BeginInvoke, func.EndInvoke, 1, "state", TaskCreationOptions.AttachedToParent);
  278. Assert.IsTrue (task.Wait (5000), "#1");
  279. Assert.IsTrue (result, "#2");
  280. Assert.AreEqual (4, task.Result, "#3");
  281. Assert.AreEqual ("state", (string) task.AsyncState, "#4");
  282. Assert.AreEqual (TaskCreationOptions.AttachedToParent, task.CreationOptions, "#5");
  283. }
  284. [Test]
  285. public void FromAsyncBeginMethod_DirectResult ()
  286. {
  287. bool result = false;
  288. bool continuationTest = false;
  289. Func<int, int> func = (i) => { result = true; return i + 3; };
  290. Task<int> task = factory.FromAsync<int> (func.BeginInvoke (1, delegate { }, null), func.EndInvoke);
  291. var cont = task.ContinueWith (_ => continuationTest = true, TaskContinuationOptions.ExecuteSynchronously);
  292. task.Wait ();
  293. cont.Wait ();
  294. Assert.IsTrue (result);
  295. Assert.IsTrue (continuationTest);
  296. Assert.AreEqual (4, task.Result);
  297. }
  298. [Test]
  299. public void FromAsyncBeginMethod_Exception ()
  300. {
  301. bool result = false;
  302. bool continuationTest = false;
  303. Func<int, int> func = (i) => { result = true; throw new ApplicationException ("bleh"); };
  304. Task<int> task = factory.FromAsync<int, int> (func.BeginInvoke, func.EndInvoke, 1, null);
  305. var cont = task.ContinueWith (_ => continuationTest = true, TaskContinuationOptions.ExecuteSynchronously);
  306. try {
  307. task.Wait ();
  308. } catch { }
  309. cont.Wait ();
  310. Assert.IsTrue (result);
  311. Assert.IsTrue (continuationTest);
  312. Assert.IsNotNull (task.Exception);
  313. var agg = task.Exception;
  314. Assert.AreEqual (1, agg.InnerExceptions.Count);
  315. Assert.That (agg.InnerExceptions[0], Is.TypeOf (typeof (ApplicationException)));
  316. Assert.AreEqual (TaskStatus.Faulted, task.Status);
  317. try {
  318. var a = task.Result;
  319. Assert.Fail ();
  320. } catch (AggregateException) {
  321. }
  322. }
  323. [Test]
  324. public void FromAsync_ArgumentsCheck ()
  325. {
  326. var result = new CompletedAsyncResult ();
  327. try {
  328. factory.FromAsync (null, l => { });
  329. Assert.Fail ("#1");
  330. } catch (ArgumentNullException) {
  331. }
  332. try {
  333. factory.FromAsync (result, null);
  334. Assert.Fail ("#2");
  335. } catch (ArgumentNullException) {
  336. }
  337. try {
  338. factory.FromAsync (result, l => { }, TaskCreationOptions.LongRunning);
  339. Assert.Fail ("#3");
  340. } catch (ArgumentOutOfRangeException) {
  341. }
  342. try {
  343. factory.FromAsync (result, l => { }, TaskCreationOptions.PreferFairness);
  344. Assert.Fail ("#4");
  345. } catch (ArgumentOutOfRangeException) {
  346. }
  347. try {
  348. factory.FromAsync (result, l => { }, TaskCreationOptions.None, null);
  349. Assert.Fail ("#5");
  350. } catch (ArgumentNullException) {
  351. }
  352. try {
  353. factory.FromAsync (null, l => { }, null, TaskCreationOptions.None);
  354. Assert.Fail ("#6");
  355. } catch (ArgumentNullException) {
  356. }
  357. try {
  358. factory.FromAsync ((a, b) => null, l => { }, null, TaskCreationOptions.LongRunning);
  359. Assert.Fail ("#7");
  360. } catch (ArgumentOutOfRangeException) {
  361. }
  362. }
  363. [Test]
  364. public void FromAsync_Completed ()
  365. {
  366. var completed = new CompletedAsyncResult ();
  367. bool? valid = null;
  368. Action<IAsyncResult> end = l => {
  369. Assert.IsFalse (Thread.CurrentThread.IsThreadPoolThread, "#2");
  370. valid = l == completed;
  371. };
  372. Task task = factory.FromAsync (completed, end);
  373. Assert.IsTrue (valid == true, "#1");
  374. }
  375. [Test]
  376. public void FromAsync_CompletedWithException ()
  377. {
  378. var completed = new CompletedAsyncResult ();
  379. Action<IAsyncResult> end = l => {
  380. throw new ApplicationException ();
  381. };
  382. Task task = factory.FromAsync (completed, end);
  383. Assert.AreEqual (TaskStatus.Faulted, task.Status, "#1");
  384. }
  385. [Test]
  386. public void FromAsync_CompletedCanceled ()
  387. {
  388. var completed = new CompletedAsyncResult ();
  389. Action<IAsyncResult> end = l => {
  390. throw new OperationCanceledException ();
  391. };
  392. Task task = factory.FromAsync (completed, end);
  393. Assert.AreEqual (TaskStatus.Canceled, task.Status, "#1");
  394. Assert.IsNull (task.Exception, "#2");
  395. }
  396. [Test]
  397. public void FromAsync_SimpleAsyncResult ()
  398. {
  399. var result = new TestAsyncResult ();
  400. bool called = false;
  401. var task = factory.FromAsync (result, l => {
  402. called = true;
  403. });
  404. Assert.IsTrue (task.Wait (1000), "#1");
  405. Assert.IsTrue (called, "#2");
  406. }
  407. [Test]
  408. public void FromAsync_ResultException ()
  409. {
  410. var result = new TestAsyncResult ();
  411. var task = factory.FromAsync (result, l => {
  412. throw new ApplicationException ();
  413. });
  414. try {
  415. Assert.IsFalse (task.Wait (1000), "#1");
  416. } catch (AggregateException) {
  417. }
  418. Assert.AreEqual (TaskStatus.Faulted, task.Status, "#2");
  419. }
  420. [Test]
  421. public void FromAsync_ReturnInt ()
  422. {
  423. var result = new TestAsyncResult ();
  424. bool called = false;
  425. var task = factory.FromAsync<int> (result, l => {
  426. called = true;
  427. return 4;
  428. });
  429. Assert.IsTrue (task.Wait (1000), "#1");
  430. Assert.IsTrue (called, "#2");
  431. Assert.AreEqual (4, task.Result, "#3");
  432. }
  433. [Test]
  434. public void FromAsync_Scheduler_Explicit ()
  435. {
  436. var result = new TestAsyncResult ();
  437. bool called = false;
  438. var scheduler = new TestScheduler ();
  439. var task = factory.FromAsync (result, l => {
  440. called = true;
  441. }, TaskCreationOptions.None, scheduler);
  442. Assert.IsTrue (task.Wait (5000), "#1");
  443. Assert.IsTrue (called, "#2");
  444. Assert.IsTrue (scheduler.ExecutedInline, "#3");
  445. }
  446. [Test]
  447. public void FromAsync_Scheduler_Implicit ()
  448. {
  449. var result = new TestAsyncResult ();
  450. bool called = false;
  451. var scheduler = new TestScheduler ();
  452. factory = new TaskFactory (scheduler);
  453. Task task = factory.FromAsync (result, l => {
  454. Assert.IsTrue (Thread.CurrentThread.IsThreadPoolThread, "#6");
  455. called = true;
  456. }, TaskCreationOptions.AttachedToParent);
  457. Assert.AreEqual (TaskCreationOptions.AttachedToParent, task.CreationOptions, "#1");
  458. Assert.IsNull (task.AsyncState, "#2");
  459. Assert.IsTrue (task.Wait (5000), "#3");
  460. Assert.IsTrue (called, "#4");
  461. Assert.IsTrue (scheduler.ExecutedInline, "#5");
  462. }
  463. [Test]
  464. public void FromAsync_BeginCallback ()
  465. {
  466. bool called = false;
  467. bool called2 = false;
  468. var task = factory.FromAsync (
  469. (a, b, c) => {
  470. if (a != "h")
  471. Assert.Fail ("#10");
  472. if ((TaskCreationOptions) c != TaskCreationOptions.AttachedToParent)
  473. Assert.Fail ("#11");
  474. Assert.IsFalse (Thread.CurrentThread.IsThreadPoolThread, "#12");
  475. called2 = true;
  476. b.Invoke (null);
  477. return null;
  478. },
  479. l => {
  480. called = true;
  481. },
  482. "h", TaskCreationOptions.AttachedToParent);
  483. Assert.AreEqual (TaskCreationOptions.None, task.CreationOptions, "#1");
  484. Assert.AreEqual (TaskCreationOptions.AttachedToParent, (TaskCreationOptions) task.AsyncState, "#2");
  485. Assert.IsTrue (task.Wait (5000), "#3");
  486. Assert.IsTrue (called, "#4");
  487. Assert.IsTrue (called2, "#5");
  488. }
  489. [Test]
  490. public void StartNewCancelled ()
  491. {
  492. var cts = new CancellationTokenSource ();
  493. cts.Cancel ();
  494. var task = factory.StartNew (() => Assert.Fail ("Should never be called"), cts.Token);
  495. try {
  496. task.Start ();
  497. } catch (InvalidOperationException) {
  498. }
  499. Assert.IsTrue (task.IsCanceled, "#2");
  500. }
  501. }
  502. }
  503. #endif