5 // Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
6 // Marek Safar <marek.safar@gmail.com>
8 // Copyright (c) 2010 Jérémie "Garuma" Laval
9 // Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
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:
18 // The above copyright notice and this permission notice shall be included in
19 // all copies or substantial portions of the Software.
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
34 using System.Threading;
35 using System.Threading.Tasks;
36 using System.Collections.Generic;
38 using NUnit.Framework;
40 namespace MonoTests.System.Threading.Tasks
43 public class TaskFactoryTests
45 class CompletedAsyncResult : IAsyncResult
47 public object AsyncState
49 get { throw new NotImplementedException (); }
52 public WaitHandle AsyncWaitHandle
54 get { throw new NotImplementedException (); }
57 public bool CompletedSynchronously
59 get { throw new NotImplementedException (); }
62 public bool IsCompleted
68 class TestAsyncResult : IAsyncResult
70 WaitHandle wh = new ManualResetEvent (true);
72 public object AsyncState
74 get { throw new NotImplementedException (); }
77 public WaitHandle AsyncWaitHandle
85 public bool CompletedSynchronously
87 get { throw new NotImplementedException (); }
90 public bool IsCompleted
96 class TestScheduler : TaskScheduler
98 public bool ExecutedInline { get; set; }
100 protected override void QueueTask (Task task)
102 throw new NotImplementedException ();
105 protected override bool TryDequeue (Task task)
107 throw new NotImplementedException ();
110 protected override bool TryExecuteTaskInline (Task task, bool taskWasPreviouslyQueued)
112 if (taskWasPreviouslyQueued)
113 throw new ArgumentException ("taskWasPreviouslyQueued");
115 if (task.Status != TaskStatus.WaitingToRun)
116 throw new ArgumentException ("task.Status");
118 ExecutedInline = true;
119 return TryExecuteTask (task);
122 protected override IEnumerable<Task> GetScheduledTasks ()
124 throw new NotImplementedException ();
134 this.factory = Task.Factory;
138 public void StartNewTest ()
141 factory.StartNew (() => result = true).Wait ();
142 Assert.IsTrue (result);
146 public void NoDefaultScheduler ()
148 Assert.IsNull (factory.Scheduler, "#1");
152 public void ContinueWhenAll_Simple ()
154 var mre = new ManualResetEventSlim (false);
156 Task[] tasks = new Task[3];
157 tasks[0] = new Task (() => { Thread.Sleep (0); Assert.IsTrue (mre.Wait (3000)); });
158 tasks[1] = new Task (() => { Assert.IsTrue (mre.Wait (3000)); });
159 tasks[2] = new Task (() => { Assert.IsTrue (mre.Wait (3000)); });
162 Task cont = factory.ContinueWhenAll (tasks, ts => {
163 Assert.AreEqual (tasks, ts, "#0");
167 foreach (Task t in tasks)
172 Assert.IsTrue (cont.Wait (1000), "#1");
173 Assert.IsTrue (ran, "#2");
177 public void ContinueWhenAll_WithMixedCompletionState ()
179 var mre = new ManualResetEventSlim ();
180 var task = Task.Factory.StartNew (() => mre.Wait (200));
181 var contFailed = task.ContinueWith (t => {}, TaskContinuationOptions.OnlyOnFaulted);
182 var contCanceled = task.ContinueWith (t => {}, TaskContinuationOptions.OnlyOnCanceled);
183 var contSuccess = task.ContinueWith (t => {}, TaskContinuationOptions.OnlyOnRanToCompletion);
186 var cont = Task.Factory.ContinueWhenAll (new Task[] { contFailed, contCanceled, contSuccess }, _ => ran = true);
192 Assert.AreEqual (TaskStatus.RanToCompletion, cont.Status);
196 public void ContinueWhenAny_Simple ()
198 var t1 = new ManualResetEvent (false);
199 var t2 = new ManualResetEvent (false);
201 var tasks = new Task[2] {
202 Task.Factory.StartNew (() => { t1.WaitOne (3000); }),
203 Task.Factory.StartNew (() => { t2.WaitOne (3000); })
207 var ct = new CancellationToken ();
208 Task cont = factory.ContinueWhenAny (tasks, t => {
209 Assert.AreEqual (tasks[0], t, "#1");
213 Assert.AreEqual (TaskStatus.WaitingForActivation, cont.Status, "#2");
217 Assert.IsTrue (cont.Wait (2000), "#10");
218 Assert.IsTrue (ran, "#11");
224 public void ContinueWhenAny_InvalidArguments ()
227 factory.ContinueWhenAny (null, delegate { });
229 } catch (ArgumentNullException) {
233 factory.ContinueWhenAny (new Task[0], delegate { });
235 } catch (ArgumentException) {
239 factory.ContinueWhenAny (new Task[] { null }, delegate { });
241 } catch (ArgumentException) {
244 var tasks = new Task [] {
245 factory.StartNew (delegate {})
249 factory.ContinueWhenAny (tasks, null);
251 } catch (ArgumentException) {
255 factory.ContinueWhenAny (tasks, delegate { }, CancellationToken.None, TaskContinuationOptions.None, null);
257 } catch (ArgumentException) {
262 public void FromAsyncBeginInvoke_WithResult ()
266 Func<int, int> func = (i) => {
267 Assert.IsTrue (Thread.CurrentThread.IsThreadPoolThread);
268 result = true; return i + 3;
271 var task = factory.FromAsync<int, int> (func.BeginInvoke, func.EndInvoke, 1, "state", TaskCreationOptions.AttachedToParent);
272 Assert.IsTrue (task.Wait (5000), "#1");
273 Assert.IsTrue (result, "#2");
274 Assert.AreEqual (4, task.Result, "#3");
275 Assert.AreEqual ("state", (string) task.AsyncState, "#4");
276 Assert.AreEqual (TaskCreationOptions.AttachedToParent, task.CreationOptions, "#5");
280 public void FromAsyncBeginMethod_DirectResult ()
283 bool continuationTest = false;
285 Func<int, int> func = (i) => { result = true; return i + 3; };
286 Task<int> task = factory.FromAsync<int> (func.BeginInvoke (1, delegate { }, null), func.EndInvoke);
287 var cont = task.ContinueWith (_ => continuationTest = true, TaskContinuationOptions.ExecuteSynchronously);
291 Assert.IsTrue (result);
292 Assert.IsTrue (continuationTest);
293 Assert.AreEqual (4, task.Result);
297 public void FromAsyncBeginMethod_Exception ()
300 bool continuationTest = false;
302 Func<int, int> func = (i) => { result = true; throw new ApplicationException ("bleh"); };
303 Task<int> task = factory.FromAsync<int, int> (func.BeginInvoke, func.EndInvoke, 1, null);
304 var cont = task.ContinueWith (_ => continuationTest = true, TaskContinuationOptions.ExecuteSynchronously);
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.IsInstanceOfType (typeof (ApplicationException), agg.InnerExceptions[0]);
316 Assert.AreEqual (TaskStatus.Faulted, task.Status);
321 } catch (AggregateException) {
326 public void FromAsync_ArgumentsCheck ()
328 var result = new CompletedAsyncResult ();
330 factory.FromAsync (null, l => { });
332 } catch (ArgumentNullException) {
336 factory.FromAsync (result, null);
338 } catch (ArgumentNullException) {
342 factory.FromAsync (result, l => { }, TaskCreationOptions.LongRunning);
344 } catch (ArgumentOutOfRangeException) {
348 factory.FromAsync (result, l => { }, TaskCreationOptions.PreferFairness);
350 } catch (ArgumentOutOfRangeException) {
354 factory.FromAsync (result, l => { }, TaskCreationOptions.None, null);
356 } catch (ArgumentNullException) {
360 factory.FromAsync (null, l => { }, null, TaskCreationOptions.None);
362 } catch (ArgumentNullException) {
366 factory.FromAsync ((a, b) => null, l => { }, null, TaskCreationOptions.LongRunning);
368 } catch (ArgumentOutOfRangeException) {
373 public void FromAsync_Completed ()
375 var completed = new CompletedAsyncResult ();
378 Action<IAsyncResult> end = l => {
379 Assert.IsFalse (Thread.CurrentThread.IsThreadPoolThread, "#2");
380 valid = l == completed;
382 Task task = factory.FromAsync (completed, end);
383 Assert.IsTrue (valid == true, "#1");
387 public void FromAsync_CompletedWithException ()
389 var completed = new CompletedAsyncResult ();
391 Action<IAsyncResult> end = l => {
392 throw new ApplicationException ();
394 Task task = factory.FromAsync (completed, end);
395 Assert.AreEqual (TaskStatus.Faulted, task.Status, "#1");
399 public void FromAsync_CompletedCanceled ()
401 var completed = new CompletedAsyncResult ();
403 Action<IAsyncResult> end = l => {
404 throw new OperationCanceledException ();
406 Task task = factory.FromAsync (completed, end);
407 Assert.AreEqual (TaskStatus.Canceled, task.Status, "#1");
408 Assert.IsNull (task.Exception, "#2");
412 public void FromAsync_SimpleAsyncResult ()
414 var result = new TestAsyncResult ();
417 var task = factory.FromAsync (result, l => {
421 Assert.IsTrue (task.Wait (1000), "#1");
422 Assert.IsTrue (called, "#2");
426 public void FromAsync_ResultException ()
428 var result = new TestAsyncResult ();
430 var task = factory.FromAsync (result, l => {
431 throw new ApplicationException ();
435 Assert.IsFalse (task.Wait (1000), "#1");
436 } catch (AggregateException) {
439 Assert.AreEqual (TaskStatus.Faulted, task.Status, "#2");
443 public void FromAsync_ReturnInt ()
445 var result = new TestAsyncResult ();
448 var task = factory.FromAsync<int> (result, l => {
453 Assert.IsTrue (task.Wait (1000), "#1");
454 Assert.IsTrue (called, "#2");
455 Assert.AreEqual (4, task.Result, "#3");
459 public void FromAsync_Scheduler_Explicit ()
461 var result = new TestAsyncResult ();
463 var scheduler = new TestScheduler ();
465 var task = factory.FromAsync (result, l => {
467 }, TaskCreationOptions.None, scheduler);
469 Assert.IsTrue (task.Wait (5000), "#1");
470 Assert.IsTrue (called, "#2");
471 Assert.IsTrue (scheduler.ExecutedInline, "#3");
475 public void FromAsync_Scheduler_Implicit ()
477 var result = new TestAsyncResult ();
479 var scheduler = new TestScheduler ();
481 factory = new TaskFactory (scheduler);
483 Task task = factory.FromAsync (result, l => {
484 Assert.IsTrue (Thread.CurrentThread.IsThreadPoolThread, "#6");
486 }, TaskCreationOptions.AttachedToParent);
488 Assert.AreEqual (TaskCreationOptions.AttachedToParent, task.CreationOptions, "#1");
489 Assert.IsNull (task.AsyncState, "#2");
490 Assert.IsTrue (task.Wait (5000), "#3");
491 Assert.IsTrue (called, "#4");
492 Assert.IsTrue (scheduler.ExecutedInline, "#5");
496 public void FromAsync_BeginCallback ()
499 bool called2 = false;
501 var task = factory.FromAsync (
506 if ((TaskCreationOptions) c != TaskCreationOptions.AttachedToParent)
509 Assert.IsFalse (Thread.CurrentThread.IsThreadPoolThread, "#12");
518 "h", TaskCreationOptions.AttachedToParent);
520 Assert.AreEqual (TaskCreationOptions.None, task.CreationOptions, "#1");
521 Assert.AreEqual (TaskCreationOptions.AttachedToParent, (TaskCreationOptions) task.AsyncState, "#2");
522 Assert.IsTrue (task.Wait (5000), "#3");
523 Assert.IsTrue (called, "#4");
524 Assert.IsTrue (called2, "#5");
528 public void StartNewCancelled ()
530 var cts = new CancellationTokenSource ();
533 var task = factory.StartNew (() => Assert.Fail ("Should never be called"), cts.Token);
536 } catch (InvalidOperationException) {
539 Assert.IsTrue (task.IsCanceled, "#2");