5 // Marek Safar <marek.safar@gmail.com>
7 // Copyright (c) 2008 Jérémie "Garuma" Laval
8 // Copyright (C) 2011 Xamarin Inc (http://www.xamarin.com)
10 // Permission is hereby granted, free of charge, to any person obtaining a copy
11 // of this software and associated documentation files (the "Software"), to deal
12 // in the Software without restriction, including without limitation the rights
13 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14 // copies of the Software, and to permit persons to whom the Software is
15 // furnished to do so, subject to the following conditions:
17 // The above copyright notice and this permission notice shall be included in
18 // all copies or substantial portions of the Software.
20 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
33 using System.Threading;
34 using System.Threading.Tasks;
35 using System.Collections.Generic;
36 using NUnit.Framework;
39 using NUnit.Framework.SyntaxHelpers;
42 namespace MonoTests.System.Threading.Tasks
45 public class TaskTests
47 class MockScheduler : TaskScheduler
49 public event Action<Task, bool> TryExecuteTaskInlineHandler;
51 protected override IEnumerable<Task> GetScheduledTasks ()
53 throw new NotImplementedException ();
56 protected override void QueueTask (Task task)
61 protected override bool TryExecuteTaskInline (Task task, bool taskWasPreviouslyQueued)
63 if (TryExecuteTaskInlineHandler != null)
64 TryExecuteTaskInlineHandler (task, taskWasPreviouslyQueued);
66 return base.TryExecuteTask (task);
70 class NonInlineableScheduler : TaskScheduler
72 protected override IEnumerable<Task> GetScheduledTasks ()
74 throw new NotImplementedException ();
77 protected override void QueueTask (Task task)
79 if (!base.TryExecuteTask (task))
80 throw new ApplicationException ();
83 protected override bool TryExecuteTaskInline (Task task, bool taskWasPreviouslyQueued)
96 tasks = new Task[max];
99 void InitWithDelegate(Action action)
101 for (int i = 0; i < max; i++) {
102 tasks[i] = Task.Factory.StartNew(action);
107 public void WaitAnyTest()
109 ParallelTestHelper.Repeat (delegate {
113 InitWithDelegate(delegate {
114 int times = Interlocked.Exchange (ref flag, 1);
116 SpinWait sw = new SpinWait ();
117 while (finished == 0) sw.SpinOnce ();
119 Interlocked.Increment (ref finished);
123 int index = Task.WaitAny(tasks, 1000);
125 Assert.AreNotEqual (-1, index, "#3");
126 Assert.AreEqual (1, flag, "#1");
127 Assert.AreEqual (1, finished, "#2");
132 public void WaitAny_Empty ()
134 Assert.AreEqual (-1, Task.WaitAny (new Task[0]));
138 public void WaitAny_Zero ()
140 Assert.AreEqual (-1, Task.WaitAny (new[] { new Task (delegate { })}, 0), "#1");
141 Assert.AreEqual (-1, Task.WaitAny (new[] { new Task (delegate { }) }, 20), "#1");
145 public void WaitAny_Cancelled ()
147 var cancelation = new CancellationTokenSource ();
148 var tasks = new Task[] {
149 new Task (delegate { }),
150 new Task (delegate { }, cancelation.Token)
153 cancelation.Cancel ();
155 Assert.AreEqual (1, Task.WaitAny (tasks, 1000), "#1");
156 Assert.IsTrue (tasks[1].IsCompleted, "#2");
157 Assert.IsTrue (tasks[1].IsCanceled, "#3");
161 public void WaitAny_CancelledWithoutExecution ()
163 var cancelation = new CancellationTokenSource ();
164 var tasks = new Task[] {
165 new Task (delegate { }),
166 new Task (delegate { })
170 var mre = new ManualResetEventSlim (false);
171 ThreadPool.QueueUserWorkItem (delegate {
172 res = Task.WaitAny (tasks, 20);
176 cancelation.Cancel ();
177 Assert.IsTrue (mre.Wait (1000), "#1");
178 Assert.AreEqual (-1, res);
182 public void WaitAny_OneException ()
184 var mre = new ManualResetEventSlim (false);
185 var tasks = new Task[] {
186 Task.Factory.StartNew (delegate { mre.Wait (1000); }),
187 Task.Factory.StartNew (delegate { throw new ApplicationException (); })
190 Assert.AreEqual (1, Task.WaitAny (tasks, 1000), "#1");
191 Assert.IsFalse (tasks[0].IsCompleted, "#2");
192 Assert.IsTrue (tasks[1].IsFaulted, "#3");
198 public void WaitAny_SingleCanceled ()
200 var src = new CancellationTokenSource ();
201 var t = Task.Factory.StartNew (() => { Thread.Sleep (200); src.Cancel (); src.Token.ThrowIfCancellationRequested (); }, src.Token);
202 Assert.AreEqual (0, Task.WaitAny (new [] { t }));
205 public void WaitAny_ManyExceptions ()
207 CountdownEvent cde = new CountdownEvent (3);
209 Task.Factory.StartNew (delegate { try { throw new ApplicationException (); } finally { cde.Signal (); } }),
210 Task.Factory.StartNew (delegate { try { throw new ApplicationException (); } finally { cde.Signal (); } }),
211 Task.Factory.StartNew (delegate { try { throw new ApplicationException (); } finally { cde.Signal (); } })
214 Assert.IsTrue (cde.Wait (1000), "#1");
217 Assert.IsTrue (Task.WaitAll (tasks, 1000), "#2");
218 } catch (AggregateException e) {
219 Assert.AreEqual (3, e.InnerExceptions.Count, "#3");
224 public void WaitAny_ManyCanceled ()
226 var cancellation = new CancellationToken (true);
228 Task.Factory.StartNew (delegate { }, cancellation),
229 Task.Factory.StartNew (delegate { }, cancellation),
230 Task.Factory.StartNew (delegate { }, cancellation)
234 Assert.IsTrue (Task.WaitAll (tasks, 1000), "#1");
235 } catch (AggregateException e) {
236 Assert.AreEqual (3, e.InnerExceptions.Count, "#2");
241 public void WaitAllTest ()
243 ParallelTestHelper.Repeat (delegate {
245 InitWithDelegate(delegate { Interlocked.Increment(ref achieved); });
247 Assert.AreEqual(max, achieved, "#1");
252 public void WaitAll_ManyTasks ()
254 for (int r = 0; r < 2000; ++r) {
255 var tasks = new Task[60];
257 for (int i = 0; i < tasks.Length; i++) {
258 tasks[i] = Task.Factory.StartNew (delegate { Thread.Sleep (0); });
261 Assert.IsTrue (Task.WaitAll (tasks, 2000));
266 public void WaitAll_Zero ()
268 Assert.IsFalse (Task.WaitAll (new Task[1] { new Task (delegate { }) }, 0), "#0");
269 Assert.IsFalse (Task.WaitAll (new Task[1] { new Task (delegate { }) }, 10), "#1");
273 public void WaitAll_WithExceptions ()
275 InitWithDelegate (delegate { throw new ApplicationException (); });
278 Task.WaitAll (tasks);
280 } catch (AggregateException e) {
281 Assert.AreEqual (6, e.InnerExceptions.Count, "#2");
284 Assert.IsNotNull (tasks[0].Exception, "#3");
288 public void WaitAll_TimeoutWithExceptionsAfter ()
290 CountdownEvent cde = new CountdownEvent (2);
291 var mre = new ManualResetEvent (false);
293 Task.Factory.StartNew (delegate { mre.WaitOne (); }),
294 Task.Factory.StartNew (delegate { try { throw new ApplicationException (); } finally { cde.Signal (); } }),
295 Task.Factory.StartNew (delegate { try { throw new ApplicationException (); } finally { cde.Signal (); } })
298 Assert.IsTrue (cde.Wait (1000), "#1");
299 Assert.IsFalse (Task.WaitAll (tasks, 1000), "#2");
304 Assert.IsTrue (Task.WaitAll (tasks, 1000), "#3");
306 } catch (AggregateException e) {
307 Assert.AreEqual (2, e.InnerExceptions.Count, "#5");
312 public void WaitAll_TimeoutWithExceptionsBefore ()
314 CountdownEvent cde = new CountdownEvent (2);
315 var mre = new ManualResetEvent (false);
317 Task.Factory.StartNew (delegate { try { throw new ApplicationException (); } finally { cde.Signal (); } }),
318 Task.Factory.StartNew (delegate { try { throw new ApplicationException (); } finally { cde.Signal (); } }),
319 Task.Factory.StartNew (delegate { mre.WaitOne (); })
322 Assert.IsTrue (cde.Wait (1000), "#1");
323 Assert.IsFalse (Task.WaitAll (tasks, 1000), "#2");
328 Assert.IsTrue (Task.WaitAll (tasks, 1000), "#3");
330 } catch (AggregateException e) {
331 Assert.AreEqual (2, e.InnerExceptions.Count, "#5");
336 public void WaitAll_Cancelled ()
338 var cancelation = new CancellationTokenSource ();
339 var tasks = new Task[] {
340 new Task (delegate { cancelation.Cancel (); }),
341 new Task (delegate { }, cancelation.Token)
347 Task.WaitAll (tasks);
349 } catch (AggregateException e) {
350 var inner = (TaskCanceledException) e.InnerException;
351 Assert.AreEqual (tasks[1], inner.Task, "#2");
354 Assert.IsTrue (tasks[0].IsCompleted, "#3");
355 Assert.IsTrue (tasks[1].IsCanceled, "#4");
360 public void WaitAll_CancelledAndTimeout ()
362 var ct = new CancellationToken (true);
363 var t1 = new Task (() => {}, ct);
364 var t2 = Task.Delay (3000);
365 Assert.IsFalse (Task.WaitAll (new[] { t1, t2 }, 10));
370 public void WaitAllExceptionThenCancelled ()
372 var cancelation = new CancellationTokenSource ();
373 var tasks = new Task[] {
374 new Task (delegate { cancelation.Cancel (); throw new ApplicationException (); }),
375 new Task (delegate { }, cancelation.Token)
381 Task.WaitAll (tasks);
383 } catch (AggregateException e) {
384 Assert.That (e.InnerException, Is.TypeOf (typeof (ApplicationException)), "#2");
385 var inner = (TaskCanceledException) e.InnerExceptions[1];
386 Assert.AreEqual (tasks[1], inner.Task, "#3");
389 Assert.IsTrue (tasks[0].IsCompleted, "#4");
390 Assert.IsTrue (tasks[1].IsCanceled, "#5");
394 public void WaitAll_StartedUnderWait ()
396 var task1 = new Task (delegate { });
398 ThreadPool.QueueUserWorkItem (delegate {
399 // Sleep little to let task to start and hit internal wait
404 Assert.IsTrue (Task.WaitAll (new [] { task1 }, 1000), "#1");
408 public void CancelBeforeStart ()
410 var src = new CancellationTokenSource ();
412 Task t = new Task (delegate { }, src.Token);
414 Assert.AreEqual (TaskStatus.Canceled, t.Status, "#1");
419 } catch (InvalidOperationException) {
424 public void Wait_CancelledTask ()
426 var src = new CancellationTokenSource ();
428 Task t = new Task (delegate { }, src.Token);
434 } catch (AggregateException e) {
435 var details = (TaskCanceledException) e.InnerException;
436 Assert.AreEqual (t, details.Task, "#1e");
442 } catch (AggregateException e) {
443 var details = (TaskCanceledException) e.InnerException;
444 Assert.AreEqual (t, details.Task, "#2e");
445 Assert.IsNull (details.Task.Exception, "#2e2");
450 public void Wait_Inlined ()
452 bool? previouslyQueued = null;
454 var scheduler = new MockScheduler ();
455 scheduler.TryExecuteTaskInlineHandler += (task, b) => {
456 previouslyQueued = b;
459 var tf = new TaskFactory (scheduler);
460 var t = tf.StartNew (() => { });
463 Assert.AreEqual (true, previouslyQueued);
466 [Test, ExpectedException (typeof (InvalidOperationException))]
467 public void CreationWhileInitiallyCanceled ()
469 var token = new CancellationToken (true);
470 var task = new Task (() => { }, token);
471 Assert.AreEqual (TaskStatus.Canceled, task.Status);
476 public void ContinueWithInvalidArguments ()
478 var task = new Task (() => { });
480 task.ContinueWith (null);
482 } catch (ArgumentException) {
486 task.ContinueWith (delegate { }, null);
488 } catch (ArgumentException) {
492 task.ContinueWith (delegate { }, TaskContinuationOptions.OnlyOnCanceled | TaskContinuationOptions.NotOnCanceled);
494 } catch (ArgumentException) {
498 task.ContinueWith (delegate { }, TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.NotOnRanToCompletion);
500 } catch (ArgumentException) {
505 public void ContinueWithOnAnyTestCase()
507 ParallelTestHelper.Repeat (delegate {
510 Task t = Task.Factory.StartNew(delegate { });
511 Task cont = t.ContinueWith(delegate { result = true; }, TaskContinuationOptions.None);
512 Assert.IsTrue (t.Wait (2000), "First wait, (status, {0})", t.Status);
513 Assert.IsTrue (cont.Wait(2000), "Cont wait, (result, {0}) (parent status, {2}) (status, {1})", result, cont.Status, t.Status);
514 Assert.IsNull(cont.Exception, "#1");
515 Assert.IsNotNull(cont, "#2");
516 Assert.IsTrue(result, "#3");
521 public void ContinueWithOnCompletedSuccessfullyTestCase()
523 ParallelTestHelper.Repeat (delegate {
526 Task t = Task.Factory.StartNew(delegate { });
527 Task cont = t.ContinueWith(delegate { result = true; }, TaskContinuationOptions.OnlyOnRanToCompletion);
528 Assert.IsTrue (t.Wait(1000), "#4");
529 Assert.IsTrue (cont.Wait(1000), "#5");
531 Assert.IsNull(cont.Exception, "#1");
532 Assert.IsNotNull(cont, "#2");
533 Assert.IsTrue(result, "#3");
538 public void ContinueWithOnAbortedTestCase()
541 bool taskResult = false;
543 CancellationTokenSource src = new CancellationTokenSource ();
544 Task t = new Task (delegate { taskResult = true; }, src.Token);
546 Task cont = t.ContinueWith (delegate { result = true; },
547 TaskContinuationOptions.OnlyOnCanceled | TaskContinuationOptions.ExecuteSynchronously);
551 Assert.AreEqual (TaskStatus.Canceled, t.Status, "#1a");
552 Assert.IsTrue (cont.IsCompleted, "#1b");
553 Assert.IsTrue (result, "#1c");
558 } catch (InvalidOperationException) {
561 Assert.IsTrue (cont.Wait (1000), "#3");
563 Assert.IsFalse (taskResult, "#4");
565 Assert.IsNull (cont.Exception, "#5");
566 Assert.AreEqual (TaskStatus.RanToCompletion, cont.Status, "#6");
570 public void ContinueWithOnFailedTestCase()
572 ParallelTestHelper.Repeat (delegate {
575 Task t = Task.Factory.StartNew(delegate { throw new Exception("foo"); });
576 Task cont = t.ContinueWith(delegate { result = true; }, TaskContinuationOptions.OnlyOnFaulted);
578 Assert.IsTrue (cont.Wait(1000), "#0");
579 Assert.IsNotNull (t.Exception, "#1");
580 Assert.IsNotNull (cont, "#2");
581 Assert.IsTrue (result, "#3");
586 public void ContinueWithWithStart ()
588 Task t = new Task<int> (() => 1);
589 t = t.ContinueWith (l => { });
593 } catch (InvalidOperationException) {
598 public void ContinueWithChildren ()
600 ParallelTestHelper.Repeat (delegate {
603 var t = Task.Factory.StartNew (() => Task.Factory.StartNew (() => {}, TaskCreationOptions.AttachedToParent));
605 var mre = new ManualResetEvent (false);
606 t.ContinueWith (l => {
611 Assert.IsTrue (mre.WaitOne (1000), "#1");
612 Assert.IsTrue (result, "#2");
617 public void ContinueWithDifferentOptionsAreCanceledTest ()
619 var mre = new ManualResetEventSlim ();
620 var task = Task.Factory.StartNew (() => mre.Wait (200));
621 var contFailed = task.ContinueWith (t => {}, TaskContinuationOptions.OnlyOnFaulted);
622 var contCanceled = task.ContinueWith (t => {}, TaskContinuationOptions.OnlyOnCanceled);
623 var contSuccess = task.ContinueWith (t => {}, TaskContinuationOptions.OnlyOnRanToCompletion);
626 contSuccess.Wait (100);
628 Assert.IsTrue (contSuccess.IsCompleted);
629 Assert.IsTrue (contFailed.IsCompleted);
630 Assert.IsTrue (contCanceled.IsCompleted);
631 Assert.IsFalse (contSuccess.IsCanceled);
632 Assert.IsTrue (contFailed.IsCanceled);
633 Assert.IsTrue (contCanceled.IsCanceled);
637 public void MultipleTasks()
639 ParallelTestHelper.Repeat (delegate {
640 bool r1 = false, r2 = false, r3 = false;
642 Task t1 = Task.Factory.StartNew(delegate {
645 Task t2 = Task.Factory.StartNew(delegate {
648 Task t3 = Task.Factory.StartNew(delegate {
656 Assert.IsTrue(r1, "#1");
657 Assert.IsTrue(r2, "#2");
658 Assert.IsTrue(r3, "#3");
663 public void WaitChildTestCase()
665 ParallelTestHelper.Repeat (delegate {
666 bool r1 = false, r2 = false, r3 = false;
667 var mre = new ManualResetEventSlim (false);
668 var mreStart = new ManualResetEventSlim (false);
670 Task t = Task.Factory.StartNew(delegate {
671 Task.Factory.StartNew(delegate {
674 }, TaskCreationOptions.AttachedToParent);
675 Task.Factory.StartNew(delegate {
677 }, TaskCreationOptions.AttachedToParent);
678 Task.Factory.StartNew(delegate {
680 }, TaskCreationOptions.AttachedToParent);
685 Assert.IsFalse (t.Wait (10), "#0a");
687 Assert.IsTrue (t.Wait (500), "#0b");
688 Assert.IsTrue(r2, "#1");
689 Assert.IsTrue(r3, "#2");
690 Assert.IsTrue(r1, "#3");
691 Assert.AreEqual (TaskStatus.RanToCompletion, t.Status, "#4");
698 public void WaitingForChildrenToComplete ()
701 var mre = new ManualResetEvent (false);
703 parent_wfc = Task.Factory.StartNew (() => {
704 nested = Task.Factory.StartNew (() => {
705 Assert.IsTrue (mre.WaitOne (4000), "parent_wfc needs to be set first");
706 Assert.IsFalse (parent_wfc.Wait (10), "#1a");
707 Assert.AreEqual (TaskStatus.WaitingForChildrenToComplete, parent_wfc.Status, "#1b");
708 }, TaskCreationOptions.AttachedToParent).ContinueWith (l => {
709 Assert.IsTrue (parent_wfc.Wait (2000), "#2a");
710 Assert.AreEqual (TaskStatus.RanToCompletion, parent_wfc.Status, "#2b");
711 }, TaskContinuationOptions.ExecuteSynchronously);
715 Assert.IsTrue (parent_wfc.Wait (2000), "#3");
716 Assert.IsTrue (nested.Wait (2000), "#4");
720 public void WaitChildWithContinuationAttachedTest ()
723 var task = new Task(() =>
725 Task.Factory.StartNew(() => {
727 }, TaskCreationOptions.AttachedToParent).ContinueWith(t => {
730 }, TaskContinuationOptions.AttachedToParent);
734 Assert.IsTrue (result);
738 public void WaitChildWithContinuationNotAttachedTest ()
740 var task = new Task(() =>
742 Task.Factory.StartNew(() => {
744 }, TaskCreationOptions.AttachedToParent).ContinueWith(t => {
749 Assert.IsTrue (task.Wait(400));
753 public void WaitChildWithNesting ()
756 var t = Task.Factory.StartNew (() => {
757 Task.Factory.StartNew (() => {
758 Task.Factory.StartNew (() => {
761 }, TaskCreationOptions.AttachedToParent);
762 }, TaskCreationOptions.AttachedToParent);
765 Assert.IsTrue (result);
769 public void DoubleWaitTest ()
771 ParallelTestHelper.Repeat (delegate {
772 var evt = new ManualResetEventSlim ();
773 var t = Task.Factory.StartNew (() => evt.Wait (5000));
774 var cntd = new CountdownEvent (2);
775 var cntd2 = new CountdownEvent (2);
777 bool r1 = false, r2 = false;
778 ThreadPool.QueueUserWorkItem (delegate { cntd.Signal (); r1 = t.Wait (1000) && t.Result; cntd2.Signal (); });
779 ThreadPool.QueueUserWorkItem (delegate { cntd.Signal (); r2 = t.Wait (1000) && t.Result; cntd2.Signal (); });
781 Assert.IsTrue (cntd.Wait (2000), "#1");
783 Assert.IsTrue (cntd2.Wait (2000), "#2");
784 Assert.IsTrue (r1, "r1");
785 Assert.IsTrue (r2, "r2");
790 public void DoubleTimeoutedWaitTest ()
792 var evt = new ManualResetEventSlim ();
793 var t = new Task (delegate { });
794 var cntd = new CountdownEvent (2);
796 bool r1 = false, r2 = false;
797 ThreadPool.QueueUserWorkItem (delegate { r1 = !t.Wait (100); cntd.Signal (); });
798 ThreadPool.QueueUserWorkItem (delegate { r2 = !t.Wait (100); cntd.Signal (); });
806 public void RunSynchronously ()
809 Task t = new Task (() => { Thread.Sleep (100); val = 1; });
810 t.RunSynchronously ();
812 Assert.AreEqual (1, val, "#1");
814 t = new Task (() => { Thread.Sleep (0); val = 2; });
816 bool? previouslyQueued = null;
818 var scheduler = new MockScheduler ();
819 scheduler.TryExecuteTaskInlineHandler += (task, b) => {
820 previouslyQueued = b;
823 t.RunSynchronously (scheduler);
825 Assert.AreEqual (2, val, "#2");
826 Assert.AreEqual (false, previouslyQueued, "#2a");
830 public void RunSynchronouslyArgumentChecks ()
832 Task t = new Task (() => { });
834 t.RunSynchronously (null);
836 } catch (ArgumentNullException) {
841 public void RunSynchronouslyWithAttachedChildren ()
844 var t = new Task (() => {
845 Task.Factory.StartNew (() => { Thread.Sleep (500); result = true; }, TaskCreationOptions.AttachedToParent);
847 t.RunSynchronously ();
848 Assert.IsTrue (result);
852 public void RunSynchronouslyOnContinuation ()
854 Task t = new Task<int> (() => 1);
855 t = t.ContinueWith (l => { });
857 t.RunSynchronously ();
859 } catch (InvalidOperationException) {
864 public void UnobservedExceptionOnFinalizerThreadTest ()
866 bool wasCalled = false;
867 TaskScheduler.UnobservedTaskException += (o, args) => {
871 var inner = new ApplicationException ();
872 Task.Factory.StartNew (() => { throw inner; });
876 GC.WaitForPendingFinalizers ();
878 Assert.IsTrue (wasCalled);
881 [Test, ExpectedException (typeof (InvalidOperationException))]
882 public void StartFinishedTaskTest ()
884 var t = Task.Factory.StartNew (delegate () { });
891 public void Start_NullArgument ()
893 var t = Task.Factory.StartNew (delegate () { });
897 } catch (ArgumentNullException) {
901 [Test, ExpectedException (typeof (InvalidOperationException))]
902 public void DisposeUnstartedTest ()
904 var t = new Task (() => { });
909 public void ThrowingUnrelatedCanceledExceptionTest ()
911 Task t = new Task (() => {
912 throw new TaskCanceledException ();
915 t.RunSynchronously ();
916 Assert.IsTrue (t.IsFaulted);
917 Assert.IsFalse (t.IsCanceled);
921 public void CanceledContinuationExecuteSynchronouslyTest ()
923 var source = new CancellationTokenSource();
924 var token = source.Token;
925 var evt = new ManualResetEventSlim ();
929 var task = Task.Factory.StartNew (() => evt.Wait (100));
930 var cont = task.ContinueWith (t => result = true, token, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
937 } catch (Exception ex) {
941 Assert.IsTrue (task.IsCompleted);
942 Assert.IsTrue (cont.IsCanceled);
943 Assert.IsFalse (result);
944 Assert.IsTrue (thrown);
948 public void WhenChildTaskErrorIsThrownParentTaskShouldBeFaulted ()
950 Task innerTask = null;
951 var testTask = new Task (() =>
953 innerTask = new Task (() =>
955 throw new InvalidOperationException ();
956 }, TaskCreationOptions.AttachedToParent);
957 innerTask.RunSynchronously ();
959 testTask.RunSynchronously ();
961 Assert.AreNotEqual (TaskStatus.Running, testTask.Status);
962 Assert.IsNotNull (innerTask);
963 Assert.IsTrue (innerTask.IsFaulted);
964 Assert.IsNotNull (testTask.Exception);
965 Assert.IsTrue (testTask.IsFaulted);
966 Assert.IsNotNull (innerTask.Exception);
970 public void WhenChildTaskErrorIsThrownOnlyOnFaultedContinuationShouldExecute ()
972 var continuationRan = false;
973 var testTask = new Task (() =>
975 var task = new Task (() =>
977 throw new InvalidOperationException();
978 }, TaskCreationOptions.AttachedToParent);
979 task.RunSynchronously ();
981 var onErrorTask = testTask.ContinueWith (x => continuationRan = true, TaskContinuationOptions.OnlyOnFaulted);
982 testTask.RunSynchronously ();
983 onErrorTask.Wait (100);
984 Assert.IsTrue (continuationRan);
988 public void WhenChildTaskErrorIsThrownNotOnFaultedContinuationShouldNotBeExecuted ()
990 var continuationRan = false;
991 var testTask = new Task (() =>
993 var task = new Task (() =>
995 throw new InvalidOperationException();
996 }, TaskCreationOptions.AttachedToParent);
997 task.RunSynchronously();
999 var onErrorTask = testTask.ContinueWith (x => continuationRan = true, TaskContinuationOptions.NotOnFaulted);
1000 testTask.RunSynchronously ();
1001 Assert.IsTrue (onErrorTask.IsCompleted);
1002 Assert.IsFalse (onErrorTask.IsFaulted);
1003 Assert.IsFalse (continuationRan);
1007 public void WhenChildTaskSeveralLevelsDeepHandlesAggregateExceptionErrorStillBubblesToParent ()
1009 var continuationRan = false;
1010 AggregateException e = null;
1011 var testTask = new Task (() =>
1013 var child1 = new Task (() =>
1015 var child2 = new Task (() =>
1017 throw new InvalidOperationException();
1018 }, TaskCreationOptions.AttachedToParent);
1019 child2.RunSynchronously ();
1020 }, TaskCreationOptions.AttachedToParent);
1022 child1.RunSynchronously();
1023 e = child1.Exception;
1024 child1.Exception.Handle (ex => true);
1026 var onErrorTask = testTask.ContinueWith (x => continuationRan = true, TaskContinuationOptions.OnlyOnFaulted);
1027 testTask.RunSynchronously ();
1028 onErrorTask.Wait (100);
1029 Assert.IsNotNull (e);
1030 Assert.IsTrue (continuationRan);
1034 public void AlreadyCompletedChildTaskShouldRunContinuationImmediately ()
1036 string result = "Failed";
1037 var testTask = new Task (() =>
1039 var child = new Task<string> (() =>
1042 }, TaskCreationOptions.AttachedToParent);
1043 child.RunSynchronously ();
1044 child.ContinueWith (x => { Thread.Sleep (50); result = x.Result; }, TaskContinuationOptions.AttachedToParent | TaskContinuationOptions.NotOnFaulted);
1046 testTask.RunSynchronously ();
1048 Assert.AreEqual ("Success", result);
1052 public void InlineNotTrashingParentRelationship ()
1054 bool r1 = false, r2 = false;
1055 var t = new Task (() => {
1056 new Task (() => { r1 = true; }, TaskCreationOptions.AttachedToParent).RunSynchronously ();
1057 Task.Factory.StartNew (() => { Thread.Sleep (100); r2 = true; }, TaskCreationOptions.AttachedToParent);
1059 t.RunSynchronously ();
1066 public void AsyncWaitHandleSet ()
1068 var task = new TaskFactory ().StartNew (() => { });
1069 var ar = (IAsyncResult)task;
1070 ar.AsyncWaitHandle.WaitOne ();
1075 public void Delay_Invalid ()
1079 } catch (ArgumentOutOfRangeException) {
1084 public void Delay_Start ()
1086 var t = Task.Delay (5000);
1089 } catch (InvalidOperationException) {
1094 public void Delay_Simple ()
1096 var t = Task.Delay (300);
1097 Assert.IsTrue (TaskStatus.WaitingForActivation == t.Status || TaskStatus.Running == t.Status, "#1");
1098 Assert.IsTrue (t.Wait (400), "#2");
1102 public void Delay_Cancelled ()
1104 var cancelation = new CancellationTokenSource ();
1106 var t = Task.Delay (5000, cancelation.Token);
1107 Assert.IsTrue (TaskStatus.WaitingForActivation == t.Status || TaskStatus.Running == t.Status, "#1");
1108 cancelation.Cancel ();
1112 } catch (AggregateException) {
1113 Assert.AreEqual (TaskStatus.Canceled, t.Status, "#3");
1116 cancelation = new CancellationTokenSource ();
1117 t = Task.Delay (Timeout.Infinite, cancelation.Token);
1118 Assert.AreEqual (TaskStatus.WaitingForActivation, t.Status, "#11");
1119 cancelation.Cancel ();
1122 Assert.Fail ("#12");
1123 } catch (AggregateException) {
1124 Assert.AreEqual (TaskStatus.Canceled, t.Status, "#13");
1129 public void WaitAny_WithNull ()
1131 var tasks = new [] {
1132 Task.FromResult (2),
1137 Task.WaitAny (tasks);
1139 } catch (ArgumentException) {
1144 public void WhenAll_WithNull ()
1147 Task.FromResult (2),
1152 Task.WhenAll (tasks);
1154 } catch (ArgumentException) {
1159 Task.WhenAll (tasks);
1161 } catch (ArgumentException) {
1166 public void WhenAll_Start ()
1168 Task[] tasks = new[] {
1169 Task.FromResult (2),
1172 var t = Task.WhenAll (tasks);
1173 Assert.AreEqual (TaskStatus.RanToCompletion, t.Status, "#1");
1178 } catch (InvalidOperationException) {
1182 new Task (delegate { }),
1185 t = Task.WhenAll (tasks);
1186 Assert.AreEqual (TaskStatus.WaitingForActivation, t.Status, "#11");
1190 Assert.Fail ("#12");
1191 } catch (InvalidOperationException) {
1196 public void WhenAll_Cancelled ()
1198 var cancelation = new CancellationTokenSource ();
1199 var tasks = new Task[] {
1200 new Task (delegate { }),
1201 new Task (delegate { }, cancelation.Token)
1204 cancelation.Cancel ();
1206 var t = Task.WhenAll (tasks);
1207 Assert.AreEqual (TaskStatus.WaitingForActivation, t.Status, "#1");
1211 Assert.IsTrue (t.Wait (1000), "#2");
1212 Assert.Fail ("#2a");
1213 } catch (AggregateException e) {
1214 Assert.That (e.InnerException, Is.TypeOf (typeof (TaskCanceledException)), "#3");
1219 public void WhenAll_Faulted ()
1221 var tcs = new TaskCompletionSource<object> ();
1222 tcs.SetException (new ApplicationException ());
1224 var tcs2 = new TaskCompletionSource<object> ();
1225 tcs2.SetException (new InvalidTimeZoneException ());
1227 var cancelation = new CancellationTokenSource ();
1228 var tasks = new Task[] {
1229 new Task (delegate { }),
1230 new Task (delegate { }, cancelation.Token),
1235 cancelation.Cancel ();
1237 var t = Task.WhenAll (tasks);
1238 Assert.AreEqual (TaskStatus.WaitingForActivation, t.Status, "#1");
1242 Assert.IsTrue (t.Wait (1000), "#2");
1243 Assert.Fail ("#2a");
1244 } catch (AggregateException e) {
1245 Assert.That (e.InnerException, Is.TypeOf (typeof (ApplicationException)), "#3");
1246 Assert.That (e.InnerExceptions[1], Is.TypeOf (typeof (InvalidTimeZoneException)), "#4");
1251 public void WhenAll ()
1253 var t1 = new Task (delegate { });
1254 var t2 = new Task (delegate { t1.Start (); });
1256 var tasks = new Task[] {
1261 var t = Task.WhenAll (tasks);
1262 Assert.AreEqual (TaskStatus.WaitingForActivation, t.Status, "#1");
1265 Assert.IsTrue (t.Wait (1000), "#2");
1269 public void WhenAllResult_WithNull ()
1272 Task.FromResult (2),
1277 Task.WhenAll<int> (tasks);
1279 } catch (ArgumentException) {
1284 Task.WhenAll<int> (tasks);
1286 } catch (ArgumentException) {
1291 public void WhenAllResult_Cancelled ()
1293 var cancelation = new CancellationTokenSource ();
1294 var tasks = new [] {
1295 new Task<int> (delegate { return 9; }),
1296 new Task<int> (delegate { return 1; }, cancelation.Token)
1299 cancelation.Cancel ();
1301 var t = Task.WhenAll (tasks);
1302 Assert.AreEqual (TaskStatus.WaitingForActivation, t.Status, "#1");
1306 Assert.IsTrue (t.Wait (1000), "#2");
1307 Assert.Fail ("#2a");
1308 } catch (AggregateException e) {
1309 Assert.That (e.InnerException, Is.TypeOf (typeof (TaskCanceledException)), "#3");
1315 } catch (AggregateException) {
1320 public void WhenAllResult ()
1322 var t1 = new Task<string> (delegate { return "a"; });
1323 var t2 = new Task<string> (delegate { t1.Start (); return "b"; });
1325 var tasks = new [] {
1330 var t = Task.WhenAll<string> (tasks);
1331 Assert.AreEqual (TaskStatus.WaitingForActivation, t.Status, "#1");
1334 Assert.IsTrue (t.Wait (1000), "#2");
1335 Assert.AreEqual (2, t.Result.Length, "#3");
1336 Assert.AreEqual ("a", t.Result[0], "#3a");
1337 Assert.AreEqual ("b", t.Result[1], "#3b");
1341 public void WhenAllResult_Completed ()
1344 Task.FromResult (1),
1348 var t = Task.WhenAll<int> (tasks);
1349 Assert.AreEqual (TaskStatus.RanToCompletion, t.Status, "#1");
1350 Assert.AreEqual (2, t.Result.Length, "#2");
1351 Assert.AreEqual (1, t.Result[0], "#2a");
1352 Assert.AreEqual (2, t.Result[1], "#2b");
1356 public void WhenAny_WithNull ()
1358 var tasks = new Task[] {
1359 Task.FromResult (2),
1364 Task.WhenAny (tasks);
1366 } catch (ArgumentException) {
1371 Task.WhenAny (tasks);
1373 } catch (ArgumentException) {
1377 Task.WhenAny (new Task[0]);
1379 } catch (ArgumentException) {
1384 public void WhenAny_Start ()
1386 Task[] tasks = new[] {
1387 Task.FromResult (2),
1390 var t = Task.WhenAny (tasks);
1391 Assert.AreEqual (TaskStatus.RanToCompletion, t.Status, "#1");
1396 } catch (InvalidOperationException) {
1400 new Task (delegate { }),
1403 t = Task.WhenAny (tasks);
1404 Assert.AreEqual (TaskStatus.WaitingForActivation, t.Status, "#11");
1408 Assert.Fail ("#12");
1409 } catch (InvalidOperationException) {
1414 public void WhenAny_Cancelled ()
1416 var cancelation = new CancellationTokenSource ();
1417 var tasks = new Task[] {
1418 new Task (delegate { }),
1419 new Task (delegate { }, cancelation.Token)
1422 cancelation.Cancel ();
1424 var t = Task.WhenAny (tasks);
1425 Assert.AreEqual (TaskStatus.RanToCompletion, t.Status, "#1");
1428 Assert.IsTrue (t.Wait (1000), "#2");
1429 Assert.AreEqual (TaskStatus.Canceled, t.Result.Status, "#3");
1433 public void WhenAny_Faulted ()
1435 var tcs = new TaskCompletionSource<object> ();
1436 tcs.SetException (new ApplicationException ());
1438 var tcs2 = new TaskCompletionSource<object> ();
1439 tcs2.SetException (new InvalidTimeZoneException ());
1441 var cancelation = new CancellationTokenSource ();
1442 var tasks = new Task[] {
1443 new Task (delegate { }),
1445 new Task (delegate { }, cancelation.Token),
1449 cancelation.Cancel ();
1451 var t = Task.WhenAny (tasks);
1452 Assert.AreEqual (TaskStatus.RanToCompletion, t.Status, "#1");
1455 Assert.IsTrue (t.Wait (1000), "#2");
1456 Assert.IsNull (t.Exception, "#3");
1458 Assert.That (t.Result.Exception.InnerException, Is.TypeOf (typeof (ApplicationException)), "#4");
1462 public void WhenAny ()
1464 var t1 = new Task (delegate { });
1465 var t2 = new Task (delegate { t1.Start (); });
1467 var tasks = new Task[] {
1472 var t = Task.WhenAny (tasks);
1473 Assert.AreEqual (TaskStatus.WaitingForActivation, t.Status, "#1");
1476 Assert.IsTrue (t.Wait (1000), "#2");
1477 Assert.IsNotNull (t.Result, "#3");
1481 public void WhenAnyResult_WithNull ()
1483 var tasks = new [] {
1484 Task.FromResult (2),
1489 Task.WhenAny<int> (tasks);
1491 } catch (ArgumentException) {
1496 Task.WhenAny<int> (tasks);
1498 } catch (ArgumentException) {
1502 Task.WhenAny<short> (new Task<short>[0]);
1504 } catch (ArgumentException) {
1509 public void WhenAnyResult_Start ()
1512 Task.FromResult (2),
1515 var t = Task.WhenAny<int> (tasks);
1516 Assert.AreEqual (TaskStatus.RanToCompletion, t.Status, "#1");
1521 } catch (InvalidOperationException) {
1525 new Task<int> (delegate { return 55; }),
1528 t = Task.WhenAny<int> (tasks);
1529 Assert.AreEqual (TaskStatus.WaitingForActivation, t.Status, "#11");
1533 Assert.Fail ("#12");
1534 } catch (InvalidOperationException) {
1539 public void WhenAnyResult_Cancelled ()
1541 var cancelation = new CancellationTokenSource ();
1542 var tasks = new [] {
1543 new Task<double> (delegate { return 1.1; }),
1544 new Task<double> (delegate { return -4.4; }, cancelation.Token)
1547 cancelation.Cancel ();
1549 var t = Task.WhenAny<double> (tasks);
1550 Assert.AreEqual (TaskStatus.RanToCompletion, t.Status, "#1");
1553 Assert.IsTrue (t.Wait (1000), "#2");
1554 Assert.AreEqual (TaskStatus.Canceled, t.Result.Status, "#3");
1558 public void WhenAnyResult_Faulted ()
1560 var tcs = new TaskCompletionSource<object> ();
1561 tcs.SetException (new ApplicationException ());
1563 var tcs2 = new TaskCompletionSource<object> ();
1564 tcs2.SetException (new InvalidTimeZoneException ());
1566 var cancelation = new CancellationTokenSource ();
1567 var tasks = new Task<object>[] {
1568 new Task<object> (delegate { return null; }),
1570 new Task<object> (delegate { return ""; }, cancelation.Token),
1574 cancelation.Cancel ();
1576 var t = Task.WhenAny<object> (tasks);
1577 Assert.AreEqual (TaskStatus.RanToCompletion, t.Status, "#1");
1580 Assert.IsTrue (t.Wait (1000), "#2");
1581 Assert.IsNull (t.Exception, "#3");
1583 Assert.That (t.Result.Exception.InnerException, Is.TypeOf (typeof (ApplicationException)), "#4");
1587 public void WhenAnyResult ()
1589 var t1 = new Task<byte> (delegate { return 3; });
1590 var t2 = new Task<byte> (delegate { t1.Start (); return 2; });
1592 var tasks = new [] {
1597 var t = Task.WhenAny<byte> (tasks);
1598 Assert.AreEqual (TaskStatus.WaitingForActivation, t.Status, "#1");
1601 Assert.IsTrue (t.Wait (1000), "#2");
1602 Assert.IsTrue (t.Result.Result > 1, "#3");
1606 public void ContinueWith_StateValue ()
1608 var t = Task.Factory.StartNew (l => {
1609 Assert.AreEqual (1, l, "a-1");
1612 var c = t.ContinueWith ((a, b) => {
1613 Assert.AreEqual (t, a, "c-1");
1614 Assert.AreEqual (2, b, "c-2");
1617 var d = t.ContinueWith ((a, b) => {
1618 Assert.AreEqual (t, a, "d-1");
1619 Assert.AreEqual (3, b, "d-2");
1623 Assert.IsTrue (d.Wait (1000), "#1");
1625 Assert.AreEqual (1, t.AsyncState, "#2");
1626 Assert.AreEqual (2, c.AsyncState, "#3");
1627 Assert.AreEqual (3, d.AsyncState, "#4");
1631 public void ContinueWith_StateValueGeneric ()
1633 var t = Task<int>.Factory.StartNew (l => {
1634 Assert.AreEqual (1, l, "a-1");
1638 var c = t.ContinueWith ((a, b) => {
1639 Assert.AreEqual (t, a, "c-1");
1640 Assert.AreEqual (2, b, "c-2");
1644 var d = t.ContinueWith ((a, b) => {
1645 Assert.AreEqual (t, a, "d-1");
1646 Assert.AreEqual (3, b, "d-2");
1650 Assert.IsTrue (d.Wait (1000), "#1");
1652 Assert.AreEqual (1, t.AsyncState, "#2");
1653 Assert.AreEqual (80, t.Result, "#2r");
1654 Assert.AreEqual (2, c.AsyncState, "#3");
1655 Assert.AreEqual ("c", c.Result, "#3r");
1656 Assert.AreEqual (3, d.AsyncState, "#4");
1657 Assert.AreEqual ('d', d.Result, "#3r");
1661 public void ContinueWith_CustomScheduleRejected ()
1663 var scheduler = new NonInlineableScheduler ();
1664 var t = Task.Factory.StartNew (delegate { }).
1665 ContinueWith (r => {}, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, scheduler);
1667 Assert.IsTrue (t.Wait (5000));
1671 public void FromResult ()
1673 var t = Task.FromResult<object> (null);
1674 Assert.IsTrue (t.IsCompleted, "#1");
1675 Assert.AreEqual (null, t.Result, "#2");
1681 public void LongRunning ()
1685 var t = new Task (() => { is_tp = Thread.CurrentThread.IsThreadPoolThread; is_bg = Thread.CurrentThread.IsBackground; });
1687 Assert.IsTrue (t.Wait (100));
1688 Assert.IsTrue ((bool)is_tp, "#1");
1689 Assert.IsTrue ((bool)is_bg, "#2");
1693 t = new Task (() => { is_tp = Thread.CurrentThread.IsThreadPoolThread; is_bg = Thread.CurrentThread.IsBackground; }, TaskCreationOptions.LongRunning);
1696 Assert.IsTrue (t.Wait (100));
1697 Assert.IsFalse ((bool) is_tp, "#11");
1698 Assert.IsTrue ((bool) is_bg, "#12");
1702 public void Run_ArgumentCheck ()
1705 Task.Run (null as Action);
1707 } catch (ArgumentNullException) {
1714 bool ranOnDefaultScheduler = false;
1715 var t = Task.Run (delegate { ranOnDefaultScheduler = Thread.CurrentThread.IsThreadPoolThread; });
1716 Assert.AreEqual (TaskCreationOptions.DenyChildAttach, t.CreationOptions, "#1");
1718 Assert.IsTrue (ranOnDefaultScheduler, "#2");
1722 public void Run_Cancel ()
1724 var t = Task.Run (() => 1, new CancellationToken (true));
1728 } catch (AggregateException) {
1731 Assert.IsTrue (t.IsCanceled, "#2");
1735 public void Run_ExistingTaskT ()
1737 var t = new Task<int> (() => 5);
1738 var t2 = Task.Run (() => { t.Start (); return t; });
1740 Assert.IsTrue (t2.Wait (1000), "#1");
1741 Assert.AreEqual (5, t2.Result, "#2");
1745 public void Run_ExistingTask ()
1747 var t = new Task (delegate { throw new Exception ("Foo"); });
1748 var t2 = Task.Run (() => { t.Start (); return t; });
1753 } catch (Exception) {}
1755 Assert.AreEqual (TaskStatus.Faulted, t.Status, "#2");
1759 public void DenyChildAttachTest ()
1761 var mre = new ManualResetEventSlim ();
1763 Task parent = Task.Factory.StartNew (() => {
1764 nested = Task.Factory.StartNew (() => mre.Wait (2000), TaskCreationOptions.AttachedToParent);
1765 }, TaskCreationOptions.DenyChildAttach);
1766 Assert.IsTrue (parent.Wait (1000), "#1");
1768 Assert.IsTrue (nested.Wait (2000), "#2");
1771 class SynchronousScheduler : TaskScheduler
1773 protected override IEnumerable<Task> GetScheduledTasks ()
1775 throw new NotImplementedException ();
1778 protected override void QueueTask (Task task)
1780 TryExecuteTaskInline (task, false);
1783 protected override bool TryExecuteTaskInline (Task task, bool taskWasPreviouslyQueued)
1785 return base.TryExecuteTask (task);
1790 public void HideSchedulerTest ()
1792 var mre = new ManualResetEventSlim ();
1793 var ranOnDefault = false;
1794 var scheduler = new SynchronousScheduler ();
1796 Task parent = Task.Factory.StartNew (() => {
1797 Task.Factory.StartNew (() => {
1798 ranOnDefault = Thread.CurrentThread.IsThreadPoolThread;
1801 }, CancellationToken.None, TaskCreationOptions.HideScheduler, scheduler);
1803 Assert.IsTrue (mre.Wait (1000), "#1");
1804 Assert.IsTrue (ranOnDefault, "#2");
1808 public void LazyCancelationTest ()
1810 var source = new CancellationTokenSource ();
1812 var parent = new Task (delegate {});
1813 var cont = parent.ContinueWith (delegate {}, source.Token, TaskContinuationOptions.LazyCancellation, TaskScheduler.Default);
1815 Assert.AreNotEqual (TaskStatus.Canceled, cont.Status, "#1");
1818 Assert.IsTrue (cont.Wait (1000), "#2");
1820 } catch (AggregateException ex) {
1821 Assert.That (ex.InnerException, Is.TypeOf (typeof (TaskCanceledException)), "#3");