TaskFactoryTest.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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 ContinueWhenAll_Simple ()
  128. {
  129. var mre = new ManualResetEventSlim (false);
  130. Task[] tasks = new Task[3];
  131. tasks[0] = new Task (() => { Thread.Sleep (0); Assert.IsTrue (mre.Wait (3000)); });
  132. tasks[1] = new Task (() => { Assert.IsTrue (mre.Wait (3000)); });
  133. tasks[2] = new Task (() => { Assert.IsTrue (mre.Wait (3000)); });
  134. bool ran = false;
  135. Task cont = factory.ContinueWhenAll (tasks, ts => {
  136. Assert.AreEqual (tasks, ts, "#0");
  137. ran = true;
  138. });
  139. foreach (Task t in tasks)
  140. t.Start ();
  141. mre.Set ();
  142. Assert.IsTrue (cont.Wait (1000), "#1");
  143. Assert.IsTrue (ran, "#2");
  144. }
  145. [Test]
  146. public void ContinueWhenAny_Simple ()
  147. {
  148. var t1 = new ManualResetEvent (false);
  149. var t2 = new ManualResetEvent (false);
  150. var tasks = new Task[2] {
  151. Task.Factory.StartNew (() => { t1.WaitOne (3000); }),
  152. Task.Factory.StartNew (() => { t2.WaitOne (3000); })
  153. };
  154. bool ran = false;
  155. var ct = new CancellationToken ();
  156. Task cont = factory.ContinueWhenAny (tasks, t => {
  157. Assert.AreEqual (tasks[0], t, "#1");
  158. ran = true;
  159. }, ct);
  160. Assert.AreEqual (TaskStatus.WaitingForActivation, cont.Status, "#2");
  161. t1.Set ();
  162. Assert.IsTrue (cont.Wait (2000), "#10");
  163. Assert.IsTrue (ran, "#11");
  164. t2.Set ();
  165. }
  166. [Test]
  167. public void ContinueWhenAny_InvalidArguments ()
  168. {
  169. try {
  170. factory.ContinueWhenAny (null, delegate { });
  171. Assert.Fail ("#1");
  172. } catch (ArgumentNullException) {
  173. }
  174. try {
  175. factory.ContinueWhenAny (new Task[0], delegate { });
  176. Assert.Fail ("#2");
  177. } catch (ArgumentException) {
  178. }
  179. try {
  180. factory.ContinueWhenAny (new Task[] { null }, delegate { });
  181. Assert.Fail ("#3");
  182. } catch (ArgumentException) {
  183. }
  184. var tasks = new Task [] {
  185. factory.StartNew (delegate {})
  186. };
  187. try {
  188. factory.ContinueWhenAny (tasks, null);
  189. Assert.Fail ("#4");
  190. } catch (ArgumentException) {
  191. }
  192. try {
  193. factory.ContinueWhenAny (tasks, delegate { }, CancellationToken.None, TaskContinuationOptions.None, null);
  194. Assert.Fail ("#5");
  195. } catch (ArgumentException) {
  196. }
  197. }
  198. [Test]
  199. public void FromAsyncBeginInvoke_WithResult ()
  200. {
  201. bool result = false;
  202. Func<int, int> func = (i) => {
  203. Assert.IsTrue (Thread.CurrentThread.IsThreadPoolThread);
  204. result = true; return i + 3;
  205. };
  206. var task = factory.FromAsync<int, int> (func.BeginInvoke, func.EndInvoke, 1, "state", TaskCreationOptions.AttachedToParent);
  207. Assert.IsTrue (task.Wait (5000), "#1");
  208. Assert.IsTrue (result, "#2");
  209. Assert.AreEqual (4, task.Result, "#3");
  210. Assert.AreEqual ("state", (string) task.AsyncState, "#4");
  211. Assert.AreEqual (TaskCreationOptions.AttachedToParent, task.CreationOptions, "#5");
  212. }
  213. [Test]
  214. public void FromAsyncBeginMethod_DirectResult ()
  215. {
  216. bool result = false;
  217. bool continuationTest = false;
  218. Func<int, int> func = (i) => { result = true; return i + 3; };
  219. Task<int> task = factory.FromAsync<int> (func.BeginInvoke (1, delegate { }, null), func.EndInvoke);
  220. var cont = task.ContinueWith (_ => continuationTest = true, TaskContinuationOptions.ExecuteSynchronously);
  221. task.Wait ();
  222. cont.Wait ();
  223. Assert.IsTrue (result);
  224. Assert.IsTrue (continuationTest);
  225. Assert.AreEqual (4, task.Result);
  226. }
  227. [Test]
  228. public void FromAsyncBeginMethod_Exception ()
  229. {
  230. bool result = false;
  231. bool continuationTest = false;
  232. Func<int, int> func = (i) => { result = true; throw new ApplicationException ("bleh"); };
  233. Task<int> task = factory.FromAsync<int, int> (func.BeginInvoke, func.EndInvoke, 1, null);
  234. var cont = task.ContinueWith (_ => continuationTest = true, TaskContinuationOptions.ExecuteSynchronously);
  235. try {
  236. task.Wait ();
  237. } catch { }
  238. cont.Wait ();
  239. Assert.IsTrue (result);
  240. Assert.IsTrue (continuationTest);
  241. Assert.IsNotNull (task.Exception);
  242. var agg = task.Exception;
  243. Assert.AreEqual (1, agg.InnerExceptions.Count);
  244. Assert.IsInstanceOfType (typeof (ApplicationException), agg.InnerExceptions[0]);
  245. Assert.AreEqual (TaskStatus.Faulted, task.Status);
  246. try {
  247. var a = task.Result;
  248. Assert.Fail ();
  249. } catch (AggregateException) {
  250. }
  251. }
  252. [Test]
  253. public void FromAsync_ArgumentsCheck ()
  254. {
  255. var result = new CompletedAsyncResult ();
  256. try {
  257. factory.FromAsync (null, l => { });
  258. Assert.Fail ("#1");
  259. } catch (ArgumentNullException) {
  260. }
  261. try {
  262. factory.FromAsync (result, null);
  263. Assert.Fail ("#2");
  264. } catch (ArgumentNullException) {
  265. }
  266. try {
  267. factory.FromAsync (result, l => { }, TaskCreationOptions.LongRunning);
  268. Assert.Fail ("#3");
  269. } catch (ArgumentOutOfRangeException) {
  270. }
  271. try {
  272. factory.FromAsync (result, l => { }, TaskCreationOptions.PreferFairness);
  273. Assert.Fail ("#4");
  274. } catch (ArgumentOutOfRangeException) {
  275. }
  276. try {
  277. factory.FromAsync (result, l => { }, TaskCreationOptions.None, null);
  278. Assert.Fail ("#5");
  279. } catch (ArgumentNullException) {
  280. }
  281. try {
  282. factory.FromAsync (null, l => { }, null, TaskCreationOptions.None);
  283. Assert.Fail ("#6");
  284. } catch (ArgumentNullException) {
  285. }
  286. try {
  287. factory.FromAsync ((a, b) => null, l => { }, null, TaskCreationOptions.LongRunning);
  288. Assert.Fail ("#7");
  289. } catch (ArgumentOutOfRangeException) {
  290. }
  291. }
  292. [Test]
  293. public void FromAsync_Completed ()
  294. {
  295. var completed = new CompletedAsyncResult ();
  296. bool? valid = null;
  297. Action<IAsyncResult> end = l => {
  298. Assert.IsFalse (Thread.CurrentThread.IsThreadPoolThread, "#2");
  299. valid = l == completed;
  300. };
  301. Task task = factory.FromAsync (completed, end);
  302. Assert.IsTrue (valid == true, "#1");
  303. }
  304. [Test]
  305. public void FromAsync_CompletedWithException ()
  306. {
  307. var completed = new CompletedAsyncResult ();
  308. Action<IAsyncResult> end = l => {
  309. throw new ApplicationException ();
  310. };
  311. Task task = factory.FromAsync (completed, end);
  312. Assert.AreEqual (TaskStatus.Faulted, task.Status, "#1");
  313. }
  314. [Test]
  315. public void FromAsync_CompletedCanceled ()
  316. {
  317. var completed = new CompletedAsyncResult ();
  318. Action<IAsyncResult> end = l => {
  319. throw new OperationCanceledException ();
  320. };
  321. Task task = factory.FromAsync (completed, end);
  322. Assert.AreEqual (TaskStatus.Canceled, task.Status, "#1");
  323. Assert.IsNull (task.Exception, "#2");
  324. }
  325. [Test]
  326. public void FromAsync_SimpleAsyncResult ()
  327. {
  328. var result = new TestAsyncResult ();
  329. bool called = false;
  330. var task = factory.FromAsync (result, l => {
  331. called = true;
  332. });
  333. Assert.IsTrue (task.Wait (1000), "#1");
  334. Assert.IsTrue (called, "#2");
  335. }
  336. [Test]
  337. public void FromAsync_ResultException ()
  338. {
  339. var result = new TestAsyncResult ();
  340. var task = factory.FromAsync (result, l => {
  341. throw new ApplicationException ();
  342. });
  343. try {
  344. Assert.IsFalse (task.Wait (1000), "#1");
  345. } catch (AggregateException) {
  346. }
  347. Assert.AreEqual (TaskStatus.Faulted, task.Status, "#2");
  348. }
  349. [Test]
  350. public void FromAsync_ReturnInt ()
  351. {
  352. var result = new TestAsyncResult ();
  353. bool called = false;
  354. var task = factory.FromAsync<int> (result, l => {
  355. called = true;
  356. return 4;
  357. });
  358. Assert.IsTrue (task.Wait (1000), "#1");
  359. Assert.IsTrue (called, "#2");
  360. Assert.AreEqual (4, task.Result, "#3");
  361. }
  362. [Test]
  363. public void FromAsync_Scheduler_Explicit ()
  364. {
  365. var result = new TestAsyncResult ();
  366. bool called = false;
  367. var scheduler = new TestScheduler ();
  368. var task = factory.FromAsync (result, l => {
  369. called = true;
  370. }, TaskCreationOptions.None, scheduler);
  371. Assert.IsTrue (task.Wait (5000), "#1");
  372. Assert.IsTrue (called, "#2");
  373. Assert.IsTrue (scheduler.ExecutedInline, "#3");
  374. }
  375. [Test]
  376. public void FromAsync_Scheduler_Implicit ()
  377. {
  378. var result = new TestAsyncResult ();
  379. bool called = false;
  380. var scheduler = new TestScheduler ();
  381. factory = new TaskFactory (scheduler);
  382. Task task = factory.FromAsync (result, l => {
  383. Assert.IsTrue (Thread.CurrentThread.IsThreadPoolThread, "#6");
  384. called = true;
  385. }, TaskCreationOptions.AttachedToParent);
  386. Assert.AreEqual (TaskCreationOptions.AttachedToParent, task.CreationOptions, "#1");
  387. Assert.IsNull (task.AsyncState, "#2");
  388. Assert.IsTrue (task.Wait (5000), "#3");
  389. Assert.IsTrue (called, "#4");
  390. Assert.IsTrue (scheduler.ExecutedInline, "#5");
  391. }
  392. [Test]
  393. public void FromAsync_BeginCallback ()
  394. {
  395. bool called = false;
  396. bool called2 = false;
  397. var task = factory.FromAsync (
  398. (a, b, c) => {
  399. if (a != "h")
  400. Assert.Fail ("#10");
  401. if ((TaskCreationOptions) c != TaskCreationOptions.AttachedToParent)
  402. Assert.Fail ("#11");
  403. Assert.IsFalse (Thread.CurrentThread.IsThreadPoolThread, "#12");
  404. called2 = true;
  405. b.Invoke (null);
  406. return null;
  407. },
  408. l => {
  409. called = true;
  410. },
  411. "h", TaskCreationOptions.AttachedToParent);
  412. Assert.AreEqual (TaskCreationOptions.None, task.CreationOptions, "#1");
  413. Assert.AreEqual (TaskCreationOptions.AttachedToParent, (TaskCreationOptions) task.AsyncState, "#2");
  414. Assert.IsTrue (task.Wait (5000), "#3");
  415. Assert.IsTrue (called, "#4");
  416. Assert.IsTrue (called2, "#5");
  417. }
  418. [Test]
  419. public void StartNewCancelled ()
  420. {
  421. var cts = new CancellationTokenSource ();
  422. cts.Cancel ();
  423. var task = factory.StartNew (() => Assert.Fail ("Should never be called"), cts.Token);
  424. try {
  425. task.Start ();
  426. } catch (InvalidOperationException) {
  427. }
  428. Assert.IsTrue (task.IsCanceled, "#2");
  429. }
  430. }
  431. }
  432. #endif