TaskTest.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  1. //
  2. // TaskTest.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. #if NET_4_0
  26. using System;
  27. using System.Threading;
  28. using System.Threading.Tasks;
  29. using NUnit.Framework;
  30. namespace MonoTests.System.Threading.Tasks
  31. {
  32. [TestFixture]
  33. public class TaskTests
  34. {
  35. Task[] tasks;
  36. const int max = 6;
  37. [SetUp]
  38. public void Setup()
  39. {
  40. tasks = new Task[max];
  41. }
  42. void InitWithDelegate(Action action)
  43. {
  44. for (int i = 0; i < max; i++) {
  45. tasks[i] = Task.Factory.StartNew(action);
  46. }
  47. }
  48. [Test]
  49. public void WaitAnyTest()
  50. {
  51. ParallelTestHelper.Repeat (delegate {
  52. int flag = 0;
  53. int finished = 0;
  54. InitWithDelegate(delegate {
  55. int times = Interlocked.Exchange (ref flag, 1);
  56. if (times == 1) {
  57. SpinWait sw = new SpinWait ();
  58. while (finished == 0) sw.SpinOnce ();
  59. } else {
  60. Interlocked.Increment (ref finished);
  61. }
  62. });
  63. int index = Task.WaitAny(tasks, 1000);
  64. Assert.AreNotEqual (-1, index, "#3");
  65. Assert.AreEqual (1, flag, "#1");
  66. Assert.AreEqual (1, finished, "#2");
  67. });
  68. }
  69. [Test]
  70. public void WaitAny_Empty ()
  71. {
  72. Assert.AreEqual (-1, Task.WaitAny (new Task[0]));
  73. }
  74. [Test]
  75. public void WaitAny_Zero ()
  76. {
  77. Assert.AreEqual (-1, Task.WaitAny (new[] { new Task (delegate { })}, 0), "#1");
  78. Assert.AreEqual (-1, Task.WaitAny (new[] { new Task (delegate { }) }, 20), "#1");
  79. }
  80. [Test]
  81. public void WaitAny_Cancelled ()
  82. {
  83. var cancelation = new CancellationTokenSource ();
  84. var tasks = new Task[] {
  85. new Task (delegate { }),
  86. new Task (delegate { }, cancelation.Token)
  87. };
  88. cancelation.Cancel ();
  89. Assert.AreEqual (1, Task.WaitAny (tasks, 1000), "#1");
  90. Assert.IsTrue (tasks[1].IsCompleted, "#2");
  91. Assert.IsTrue (tasks[1].IsCanceled, "#3");
  92. }
  93. [Test]
  94. public void WaitAny_CancelledWithoutExecution ()
  95. {
  96. var cancelation = new CancellationTokenSource ();
  97. var tasks = new Task[] {
  98. new Task (delegate { }),
  99. new Task (delegate { })
  100. };
  101. int res = 0;
  102. var mre = new ManualResetEventSlim (false);
  103. ThreadPool.QueueUserWorkItem (delegate {
  104. res = Task.WaitAny (tasks, 20);
  105. mre.Set ();
  106. });
  107. cancelation.Cancel ();
  108. Assert.IsTrue (mre.Wait (1000), "#1");
  109. Assert.AreEqual (-1, res);
  110. }
  111. [Test]
  112. public void WaitAny_OneException ()
  113. {
  114. var mre = new ManualResetEventSlim (false);
  115. var tasks = new Task[] {
  116. Task.Factory.StartNew (delegate { mre.Wait (1000); }),
  117. Task.Factory.StartNew (delegate { throw new ApplicationException (); })
  118. };
  119. Assert.AreEqual (1, Task.WaitAny (tasks, 1000), "#1");
  120. Assert.IsFalse (tasks[0].IsCompleted, "#2");
  121. Assert.IsTrue (tasks[1].IsFaulted, "#3");
  122. mre.Set ();
  123. }
  124. [Test]
  125. public void WaitAny_SingleCanceled ()
  126. {
  127. var src = new CancellationTokenSource ();
  128. var t = Task.Factory.StartNew (() => { Thread.Sleep (200); src.Cancel (); src.Token.ThrowIfCancellationRequested (); }, src.Token);
  129. Assert.AreEqual (0, Task.WaitAny (new [] { t }));
  130. }
  131. public void WaitAny_ManyExceptions ()
  132. {
  133. CountdownEvent cde = new CountdownEvent (3);
  134. var tasks = new [] {
  135. Task.Factory.StartNew (delegate { try { throw new ApplicationException (); } finally { cde.Signal (); } }),
  136. Task.Factory.StartNew (delegate { try { throw new ApplicationException (); } finally { cde.Signal (); } }),
  137. Task.Factory.StartNew (delegate { try { throw new ApplicationException (); } finally { cde.Signal (); } })
  138. };
  139. Assert.IsTrue (cde.Wait (1000), "#1");
  140. try {
  141. Assert.IsTrue (Task.WaitAll (tasks, 1000), "#2");
  142. } catch (AggregateException e) {
  143. Assert.AreEqual (3, e.InnerExceptions.Count, "#3");
  144. }
  145. }
  146. [Test]
  147. public void WaitAny_ManyCanceled ()
  148. {
  149. var cancellation = new CancellationToken (true);
  150. var tasks = new[] {
  151. Task.Factory.StartNew (delegate { }, cancellation),
  152. Task.Factory.StartNew (delegate { }, cancellation),
  153. Task.Factory.StartNew (delegate { }, cancellation)
  154. };
  155. try {
  156. Assert.IsTrue (Task.WaitAll (tasks, 1000), "#1");
  157. } catch (AggregateException e) {
  158. Assert.AreEqual (3, e.InnerExceptions.Count, "#2");
  159. }
  160. }
  161. [Test]
  162. public void WaitAllTest()
  163. {
  164. ParallelTestHelper.Repeat (delegate {
  165. int achieved = 0;
  166. InitWithDelegate(delegate { Interlocked.Increment(ref achieved); });
  167. Task.WaitAll(tasks);
  168. Assert.AreEqual(max, achieved, "#1");
  169. });
  170. }
  171. [Test]
  172. public void WaitAll_Zero ()
  173. {
  174. Assert.IsFalse (Task.WaitAll (new Task[1] { new Task (delegate { }) }, 0), "#0");
  175. Assert.IsFalse (Task.WaitAll (new Task[1] { new Task (delegate { }) }, 10), "#1");
  176. }
  177. [Test]
  178. public void WaitAll_WithExceptions ()
  179. {
  180. InitWithDelegate (delegate { throw new ApplicationException (); });
  181. try {
  182. Task.WaitAll (tasks);
  183. Assert.Fail ("#1");
  184. } catch (AggregateException e) {
  185. Assert.AreEqual (6, e.InnerExceptions.Count, "#2");
  186. }
  187. Assert.IsNotNull (tasks[0].Exception, "#3");
  188. }
  189. [Test]
  190. public void WaitAll_TimeoutWithExceptionsAfter ()
  191. {
  192. CountdownEvent cde = new CountdownEvent (2);
  193. var mre = new ManualResetEvent (false);
  194. var tasks = new[] {
  195. Task.Factory.StartNew (delegate { mre.WaitOne (); }),
  196. Task.Factory.StartNew (delegate { try { throw new ApplicationException (); } finally { cde.Signal (); } }),
  197. Task.Factory.StartNew (delegate { try { throw new ApplicationException (); } finally { cde.Signal (); } })
  198. };
  199. Assert.IsTrue (cde.Wait (1000), "#1");
  200. Assert.IsFalse (Task.WaitAll (tasks, 1000), "#2");
  201. mre.Set ();
  202. try {
  203. Assert.IsTrue (Task.WaitAll (tasks, 1000), "#3");
  204. Assert.Fail ("#4");
  205. } catch (AggregateException e) {
  206. Assert.AreEqual (2, e.InnerExceptions.Count, "#5");
  207. }
  208. }
  209. [Test]
  210. public void WaitAll_TimeoutWithExceptionsBefore ()
  211. {
  212. CountdownEvent cde = new CountdownEvent (2);
  213. var mre = new ManualResetEvent (false);
  214. var tasks = new[] {
  215. Task.Factory.StartNew (delegate { try { throw new ApplicationException (); } finally { cde.Signal (); } }),
  216. Task.Factory.StartNew (delegate { try { throw new ApplicationException (); } finally { cde.Signal (); } }),
  217. Task.Factory.StartNew (delegate { mre.WaitOne (); })
  218. };
  219. Assert.IsTrue (cde.Wait (1000), "#1");
  220. Assert.IsFalse (Task.WaitAll (tasks, 1000), "#2");
  221. mre.Set ();
  222. try {
  223. Assert.IsTrue (Task.WaitAll (tasks, 1000), "#3");
  224. Assert.Fail ("#4");
  225. } catch (AggregateException e) {
  226. Assert.AreEqual (2, e.InnerExceptions.Count, "#5");
  227. }
  228. }
  229. [Test]
  230. public void WaitAll_Cancelled ()
  231. {
  232. var cancelation = new CancellationTokenSource ();
  233. var tasks = new Task[] {
  234. new Task (delegate { cancelation.Cancel (); }),
  235. new Task (delegate { }, cancelation.Token)
  236. };
  237. tasks[0].Start ();
  238. try {
  239. Task.WaitAll (tasks);
  240. Assert.Fail ("#1");
  241. } catch (AggregateException e) {
  242. var inner = (TaskCanceledException) e.InnerException;
  243. Assert.AreEqual (tasks[1], inner.Task, "#2");
  244. }
  245. Assert.IsTrue (tasks[0].IsCompleted, "#3");
  246. Assert.IsTrue (tasks[1].IsCanceled, "#4");
  247. }
  248. [Test]
  249. public void WaitAllExceptionThenCancelled ()
  250. {
  251. var cancelation = new CancellationTokenSource ();
  252. var tasks = new Task[] {
  253. new Task (delegate { cancelation.Cancel (); throw new ApplicationException (); }),
  254. new Task (delegate { }, cancelation.Token)
  255. };
  256. tasks[0].Start ();
  257. try {
  258. Task.WaitAll (tasks);
  259. Assert.Fail ("#1");
  260. } catch (AggregateException e) {
  261. Assert.IsInstanceOfType (typeof (ApplicationException), e.InnerException, "#2");
  262. var inner = (TaskCanceledException) e.InnerExceptions[1];
  263. Assert.AreEqual (tasks[1], inner.Task, "#3");
  264. }
  265. Assert.IsTrue (tasks[0].IsCompleted, "#4");
  266. Assert.IsTrue (tasks[1].IsCanceled, "#5");
  267. }
  268. [Test]
  269. public void WaitAll_StartedUnderWait ()
  270. {
  271. var task1 = new Task (delegate { });
  272. ThreadPool.QueueUserWorkItem (delegate {
  273. // Sleep little to let task to start and hit internal wait
  274. Thread.Sleep (20);
  275. task1.Start ();
  276. });
  277. Assert.IsTrue (Task.WaitAll (new [] { task1 }, 1000), "#1");
  278. }
  279. [Test]
  280. public void CancelBeforeStart ()
  281. {
  282. var src = new CancellationTokenSource ();
  283. Task t = new Task (delegate { }, src.Token);
  284. src.Cancel ();
  285. Assert.AreEqual (TaskStatus.Canceled, t.Status, "#1");
  286. try {
  287. t.Start ();
  288. Assert.Fail ("#2");
  289. } catch (InvalidOperationException) {
  290. }
  291. }
  292. [Test]
  293. public void Wait_CancelledTask ()
  294. {
  295. var src = new CancellationTokenSource ();
  296. Task t = new Task (delegate { }, src.Token);
  297. src.Cancel ();
  298. try {
  299. t.Wait (1000);
  300. Assert.Fail ("#1");
  301. } catch (AggregateException e) {
  302. var details = (TaskCanceledException) e.InnerException;
  303. Assert.AreEqual (t, details.Task, "#1e");
  304. }
  305. try {
  306. t.Wait ();
  307. Assert.Fail ("#2");
  308. } catch (AggregateException e) {
  309. var details = (TaskCanceledException) e.InnerException;
  310. Assert.AreEqual (t, details.Task, "#2e");
  311. Assert.IsNull (details.Task.Exception, "#2e2");
  312. }
  313. }
  314. [Test, ExpectedException (typeof (InvalidOperationException))]
  315. public void CreationWhileInitiallyCanceled ()
  316. {
  317. var token = new CancellationToken (true);
  318. var task = new Task (() => { }, token);
  319. Assert.AreEqual (TaskStatus.Canceled, task.Status);
  320. task.Start ();
  321. }
  322. [Test]
  323. public void ContinueWithInvalidArguments ()
  324. {
  325. var task = new Task (() => { });
  326. try {
  327. task.ContinueWith (null);
  328. Assert.Fail ("#1");
  329. } catch (ArgumentException) {
  330. }
  331. try {
  332. task.ContinueWith (delegate { }, null);
  333. Assert.Fail ("#2");
  334. } catch (ArgumentException) {
  335. }
  336. try {
  337. task.ContinueWith (delegate { }, TaskContinuationOptions.OnlyOnCanceled | TaskContinuationOptions.NotOnCanceled);
  338. Assert.Fail ("#3");
  339. } catch (ArgumentException) {
  340. }
  341. try {
  342. task.ContinueWith (delegate { }, TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.NotOnRanToCompletion);
  343. Assert.Fail ("#4");
  344. } catch (ArgumentException) {
  345. }
  346. }
  347. [Test]
  348. public void ContinueWithOnAnyTestCase()
  349. {
  350. ParallelTestHelper.Repeat (delegate {
  351. bool result = false;
  352. Task t = Task.Factory.StartNew(delegate { });
  353. Task cont = t.ContinueWith(delegate { result = true; }, TaskContinuationOptions.None);
  354. Assert.IsTrue (t.Wait (2000), "First wait, (status, {0})", t.Status);
  355. Assert.IsTrue (cont.Wait(2000), "Cont wait, (result, {0}) (parent status, {2}) (status, {1})", result, cont.Status, t.Status);
  356. Assert.IsNull(cont.Exception, "#1");
  357. Assert.IsNotNull(cont, "#2");
  358. Assert.IsTrue(result, "#3");
  359. });
  360. }
  361. [Test]
  362. public void ContinueWithOnCompletedSuccessfullyTestCase()
  363. {
  364. ParallelTestHelper.Repeat (delegate {
  365. bool result = false;
  366. Task t = Task.Factory.StartNew(delegate { });
  367. Task cont = t.ContinueWith(delegate { result = true; }, TaskContinuationOptions.OnlyOnRanToCompletion);
  368. Assert.IsTrue (t.Wait(1000), "#4");
  369. Assert.IsTrue (cont.Wait(1000), "#5");
  370. Assert.IsNull(cont.Exception, "#1");
  371. Assert.IsNotNull(cont, "#2");
  372. Assert.IsTrue(result, "#3");
  373. });
  374. }
  375. [Test]
  376. public void ContinueWithOnAbortedTestCase()
  377. {
  378. bool result = false;
  379. bool taskResult = false;
  380. CancellationTokenSource src = new CancellationTokenSource ();
  381. Task t = new Task (delegate { taskResult = true; }, src.Token);
  382. Task cont = t.ContinueWith (delegate { result = true; },
  383. TaskContinuationOptions.OnlyOnCanceled | TaskContinuationOptions.ExecuteSynchronously);
  384. src.Cancel ();
  385. Assert.AreEqual (TaskStatus.Canceled, t.Status, "#1a");
  386. Assert.IsTrue (cont.IsCompleted, "#1b");
  387. Assert.IsTrue (result, "#1c");
  388. try {
  389. t.Start ();
  390. Assert.Fail ("#2");
  391. } catch (InvalidOperationException) {
  392. }
  393. Assert.IsTrue (cont.Wait (1000), "#3");
  394. Assert.IsFalse (taskResult, "#4");
  395. Assert.IsNull (cont.Exception, "#5");
  396. Assert.AreEqual (TaskStatus.RanToCompletion, cont.Status, "#6");
  397. }
  398. [Test]
  399. public void ContinueWithOnFailedTestCase()
  400. {
  401. ParallelTestHelper.Repeat (delegate {
  402. bool result = false;
  403. Task t = Task.Factory.StartNew(delegate { throw new Exception("foo"); });
  404. Task cont = t.ContinueWith(delegate { result = true; }, TaskContinuationOptions.OnlyOnFaulted);
  405. Assert.IsTrue (cont.Wait(1000), "#0");
  406. Assert.IsNotNull (t.Exception, "#1");
  407. Assert.IsNotNull (cont, "#2");
  408. Assert.IsTrue (result, "#3");
  409. });
  410. }
  411. [Test]
  412. public void ContinueWithWithStart ()
  413. {
  414. Task t = new Task<int> (() => 1);
  415. t = t.ContinueWith (l => { });
  416. try {
  417. t.Start ();
  418. Assert.Fail ();
  419. } catch (InvalidOperationException) {
  420. }
  421. }
  422. [Test]
  423. public void ContinueWithChildren ()
  424. {
  425. ParallelTestHelper.Repeat (delegate {
  426. bool result = false;
  427. var t = Task.Factory.StartNew (() => Task.Factory.StartNew (() => {}, TaskCreationOptions.AttachedToParent));
  428. var mre = new ManualResetEvent (false);
  429. t.ContinueWith (l => {
  430. result = true;
  431. mre.Set ();
  432. });
  433. Assert.IsTrue (mre.WaitOne (1000), "#1");
  434. Assert.IsTrue (result, "#2");
  435. }, 2);
  436. }
  437. [Test]
  438. public void MultipleTasks()
  439. {
  440. ParallelTestHelper.Repeat (delegate {
  441. bool r1 = false, r2 = false, r3 = false;
  442. Task t1 = Task.Factory.StartNew(delegate {
  443. r1 = true;
  444. });
  445. Task t2 = Task.Factory.StartNew(delegate {
  446. r2 = true;
  447. });
  448. Task t3 = Task.Factory.StartNew(delegate {
  449. r3 = true;
  450. });
  451. t1.Wait(2000);
  452. t2.Wait(2000);
  453. t3.Wait(2000);
  454. Assert.IsTrue(r1, "#1");
  455. Assert.IsTrue(r2, "#2");
  456. Assert.IsTrue(r3, "#3");
  457. }, 100);
  458. }
  459. [Test]
  460. public void WaitChildTestCase()
  461. {
  462. ParallelTestHelper.Repeat (delegate {
  463. bool r1 = false, r2 = false, r3 = false;
  464. var mre = new ManualResetEvent (false);
  465. Task t = Task.Factory.StartNew(delegate {
  466. Task.Factory.StartNew(delegate {
  467. r1 = true;
  468. mre.Set ();
  469. }, TaskCreationOptions.AttachedToParent);
  470. Task.Factory.StartNew(delegate {
  471. Assert.IsTrue (mre.WaitOne (1000), "#0");
  472. r2 = true;
  473. }, TaskCreationOptions.AttachedToParent);
  474. Task.Factory.StartNew(delegate {
  475. Assert.IsTrue (mre.WaitOne (1000), "#0");
  476. r3 = true;
  477. }, TaskCreationOptions.AttachedToParent);
  478. });
  479. Assert.IsTrue (t.Wait(2000), "#0");
  480. Assert.IsTrue(r2, "#1");
  481. Assert.IsTrue(r3, "#2");
  482. Assert.IsTrue(r1, "#3");
  483. Assert.AreEqual (TaskStatus.RanToCompletion, t.Status, "#4");
  484. }, 10);
  485. }
  486. [Test]
  487. public void DoubleWaitTest ()
  488. {
  489. ParallelTestHelper.Repeat (delegate {
  490. Console.WriteLine ("run");
  491. var evt = new ManualResetEventSlim ();
  492. var t = Task.Factory.StartNew (() => evt.Wait (2000));
  493. var cntd = new CountdownEvent (2);
  494. bool r1 = false, r2 = false;
  495. ThreadPool.QueueUserWorkItem (delegate { cntd.Signal (); r1 = t.Wait (1000); Console.WriteLine ("out 1 {0}", r1); cntd.Signal (); });
  496. ThreadPool.QueueUserWorkItem (delegate { cntd.Signal (); r2 = t.Wait (1000); Console.WriteLine ("out 2 {0}", r2); cntd.Signal (); });
  497. cntd.Wait (2000);
  498. cntd.Reset ();
  499. evt.Set ();
  500. cntd.Wait (2000);
  501. Assert.IsTrue (r1);
  502. Assert.IsTrue (r2);
  503. }, 5);
  504. }
  505. [Test]
  506. public void DoubleTimeoutedWaitTest ()
  507. {
  508. var evt = new ManualResetEventSlim ();
  509. var t = new Task (delegate { });
  510. var cntd = new CountdownEvent (2);
  511. bool r1 = false, r2 = false;
  512. ThreadPool.QueueUserWorkItem (delegate { r1 = !t.Wait (500); cntd.Signal (); });
  513. ThreadPool.QueueUserWorkItem (delegate { r2 = !t.Wait (500); cntd.Signal (); });
  514. cntd.Wait (2000);
  515. Assert.IsTrue (r1);
  516. Assert.IsTrue (r2);
  517. }
  518. [Test]
  519. public void ExecuteSynchronouslyTest ()
  520. {
  521. var val = 0;
  522. Task t = new Task (() => { Thread.Sleep (100); val = 1; });
  523. t.RunSynchronously ();
  524. Assert.AreEqual (1, val);
  525. }
  526. [Test]
  527. public void RunSynchronouslyArgumentChecks ()
  528. {
  529. Task t = new Task (() => { });
  530. try {
  531. t.RunSynchronously (null);
  532. Assert.Fail ("#1");
  533. } catch (ArgumentNullException) {
  534. }
  535. }
  536. [Test]
  537. public void UnobservedExceptionOnFinalizerThreadTest ()
  538. {
  539. bool wasCalled = false;
  540. TaskScheduler.UnobservedTaskException += (o, args) => {
  541. wasCalled = true;
  542. args.SetObserved ();
  543. };
  544. var inner = new ApplicationException ();
  545. Task.Factory.StartNew (() => { throw inner; });
  546. Thread.Sleep (1000);
  547. GC.Collect ();
  548. Thread.Sleep (1000);
  549. GC.WaitForPendingFinalizers ();
  550. Assert.IsTrue (wasCalled);
  551. }
  552. [Test, ExpectedException (typeof (InvalidOperationException))]
  553. public void StartFinishedTaskTest ()
  554. {
  555. var t = Task.Factory.StartNew (delegate () { });
  556. t.Wait ();
  557. t.Start ();
  558. }
  559. [Test]
  560. public void Start_NullArgument ()
  561. {
  562. var t = Task.Factory.StartNew (delegate () { });
  563. try {
  564. t.Start (null);
  565. Assert.Fail ();
  566. } catch (ArgumentNullException) {
  567. }
  568. }
  569. [Test, ExpectedException (typeof (InvalidOperationException))]
  570. public void DisposeUnstartedTest ()
  571. {
  572. var t = new Task (() => { });
  573. t.Dispose ();
  574. }
  575. [Test]
  576. public void ThrowingUnrelatedCanceledExceptionTest ()
  577. {
  578. Task t = new Task (() => {
  579. throw new TaskCanceledException ();
  580. });
  581. t.RunSynchronously ();
  582. Assert.IsTrue (t.IsFaulted);
  583. Assert.IsFalse (t.IsCanceled);
  584. }
  585. #if NET_4_5
  586. [Test]
  587. public void WaitAny_WithNull ()
  588. {
  589. var tasks = new [] {
  590. Task.FromResult (2),
  591. null
  592. };
  593. try {
  594. Task.WaitAny (tasks);
  595. Assert.Fail ();
  596. } catch (ArgumentException) {
  597. }
  598. }
  599. [Test]
  600. public void FromResult ()
  601. {
  602. var t = Task.FromResult<object> (null);
  603. Assert.IsTrue (t.IsCompleted, "#1");
  604. Assert.AreEqual (null, t.Result, "#2");
  605. t.Dispose ();
  606. t.Dispose ();
  607. }
  608. [Test]
  609. public void Run_ArgumentCheck ()
  610. {
  611. try {
  612. Task.Run (null as Action);
  613. Assert.Fail ("#1");
  614. } catch (ArgumentNullException) {
  615. }
  616. }
  617. [Test]
  618. public void Run ()
  619. {
  620. var t = Task.Run (delegate { });
  621. Assert.AreEqual (TaskCreationOptions.DenyChildAttach, t.CreationOptions, "#1");
  622. t.Wait ();
  623. }
  624. [Test]
  625. public void Run_Cancel ()
  626. {
  627. var t = Task.Run (() => 1, new CancellationToken (true));
  628. try {
  629. var r = t.Result;
  630. Assert.Fail ("#1");
  631. } catch (AggregateException) {
  632. }
  633. Assert.IsTrue (t.IsCanceled, "#2");
  634. }
  635. [Test]
  636. public void Run_ExistingTask ()
  637. {
  638. var t = new Task<int> (() => 5);
  639. var t2 = Task.Run (() => { t.Start (); return t; });
  640. Assert.IsTrue (t2.Wait (1000), "#1");
  641. Assert.AreEqual (5, t2.Result, "#2");
  642. }
  643. #endif
  644. }
  645. }
  646. #endif