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 Delay_TimeManagement ()
1131 var delay1 = Task.Delay(50);
1132 var delay2 = Task.Delay(25);
1133 Assert.IsTrue (Task.WhenAny(new[] { delay1, delay2 }).Wait (1000));
1134 Assert.AreEqual (TaskStatus.RanToCompletion, delay2.Status);
1138 public void WaitAny_WithNull ()
1140 var tasks = new [] {
1141 Task.FromResult (2),
1146 Task.WaitAny (tasks);
1148 } catch (ArgumentException) {
1153 public void WhenAll_WithNull ()
1156 Task.FromResult (2),
1161 Task.WhenAll (tasks);
1163 } catch (ArgumentException) {
1168 Task.WhenAll (tasks);
1170 } catch (ArgumentException) {
1175 public void WhenAll_Start ()
1177 Task[] tasks = new[] {
1178 Task.FromResult (2),
1181 var t = Task.WhenAll (tasks);
1182 Assert.AreEqual (TaskStatus.RanToCompletion, t.Status, "#1");
1187 } catch (InvalidOperationException) {
1191 new Task (delegate { }),
1194 t = Task.WhenAll (tasks);
1195 Assert.AreEqual (TaskStatus.WaitingForActivation, t.Status, "#11");
1199 Assert.Fail ("#12");
1200 } catch (InvalidOperationException) {
1205 public void WhenAll_Cancelled ()
1207 var cancelation = new CancellationTokenSource ();
1208 var tasks = new Task[] {
1209 new Task (delegate { }),
1210 new Task (delegate { }, cancelation.Token)
1213 cancelation.Cancel ();
1215 var t = Task.WhenAll (tasks);
1216 Assert.AreEqual (TaskStatus.WaitingForActivation, t.Status, "#1");
1220 Assert.IsTrue (t.Wait (1000), "#2");
1221 Assert.Fail ("#2a");
1222 } catch (AggregateException e) {
1223 Assert.That (e.InnerException, Is.TypeOf (typeof (TaskCanceledException)), "#3");
1228 public void WhenAll_Faulted ()
1230 var tcs = new TaskCompletionSource<object> ();
1231 tcs.SetException (new ApplicationException ());
1233 var tcs2 = new TaskCompletionSource<object> ();
1234 tcs2.SetException (new InvalidTimeZoneException ());
1236 var cancelation = new CancellationTokenSource ();
1237 var tasks = new Task[] {
1238 new Task (delegate { }),
1239 new Task (delegate { }, cancelation.Token),
1244 cancelation.Cancel ();
1246 var t = Task.WhenAll (tasks);
1247 Assert.AreEqual (TaskStatus.WaitingForActivation, t.Status, "#1");
1251 Assert.IsTrue (t.Wait (1000), "#2");
1252 Assert.Fail ("#2a");
1253 } catch (AggregateException e) {
1254 Assert.That (e.InnerException, Is.TypeOf (typeof (ApplicationException)), "#3");
1255 Assert.That (e.InnerExceptions[1], Is.TypeOf (typeof (InvalidTimeZoneException)), "#4");
1260 public void WhenAll ()
1262 var t1 = new Task (delegate { });
1263 var t2 = new Task (delegate { t1.Start (); });
1265 var tasks = new Task[] {
1270 var t = Task.WhenAll (tasks);
1271 Assert.AreEqual (TaskStatus.WaitingForActivation, t.Status, "#1");
1274 Assert.IsTrue (t.Wait (1000), "#2");
1278 public void WhenAllResult_WithNull ()
1281 Task.FromResult (2),
1286 Task.WhenAll<int> (tasks);
1288 } catch (ArgumentException) {
1293 Task.WhenAll<int> (tasks);
1295 } catch (ArgumentException) {
1300 public void WhenAllResult_Cancelled ()
1302 var cancelation = new CancellationTokenSource ();
1303 var tasks = new [] {
1304 new Task<int> (delegate { return 9; }),
1305 new Task<int> (delegate { return 1; }, cancelation.Token)
1308 cancelation.Cancel ();
1310 var t = Task.WhenAll (tasks);
1311 Assert.AreEqual (TaskStatus.WaitingForActivation, t.Status, "#1");
1315 Assert.IsTrue (t.Wait (1000), "#2");
1316 Assert.Fail ("#2a");
1317 } catch (AggregateException e) {
1318 Assert.That (e.InnerException, Is.TypeOf (typeof (TaskCanceledException)), "#3");
1324 } catch (AggregateException) {
1329 public void WhenAllResult ()
1331 var t1 = new Task<string> (delegate { return "a"; });
1332 var t2 = new Task<string> (delegate { t1.Start (); return "b"; });
1334 var tasks = new [] {
1339 var t = Task.WhenAll<string> (tasks);
1340 Assert.AreEqual (TaskStatus.WaitingForActivation, t.Status, "#1");
1343 Assert.IsTrue (t.Wait (1000), "#2");
1344 Assert.AreEqual (2, t.Result.Length, "#3");
1345 Assert.AreEqual ("a", t.Result[0], "#3a");
1346 Assert.AreEqual ("b", t.Result[1], "#3b");
1350 public void WhenAllResult_Completed ()
1353 Task.FromResult (1),
1357 var t = Task.WhenAll<int> (tasks);
1358 Assert.AreEqual (TaskStatus.RanToCompletion, t.Status, "#1");
1359 Assert.AreEqual (2, t.Result.Length, "#2");
1360 Assert.AreEqual (1, t.Result[0], "#2a");
1361 Assert.AreEqual (2, t.Result[1], "#2b");
1365 public void WhenAny_WithNull ()
1367 var tasks = new Task[] {
1368 Task.FromResult (2),
1373 Task.WhenAny (tasks);
1375 } catch (ArgumentException) {
1380 Task.WhenAny (tasks);
1382 } catch (ArgumentException) {
1386 Task.WhenAny (new Task[0]);
1388 } catch (ArgumentException) {
1393 public void WhenAny_Start ()
1395 Task[] tasks = new[] {
1396 Task.FromResult (2),
1399 var t = Task.WhenAny (tasks);
1400 Assert.AreEqual (TaskStatus.RanToCompletion, t.Status, "#1");
1405 } catch (InvalidOperationException) {
1409 new Task (delegate { }),
1412 t = Task.WhenAny (tasks);
1413 Assert.AreEqual (TaskStatus.WaitingForActivation, t.Status, "#11");
1417 Assert.Fail ("#12");
1418 } catch (InvalidOperationException) {
1423 public void WhenAny_Cancelled ()
1425 var cancelation = new CancellationTokenSource ();
1426 var tasks = new Task[] {
1427 new Task (delegate { }),
1428 new Task (delegate { }, cancelation.Token)
1431 cancelation.Cancel ();
1433 var t = Task.WhenAny (tasks);
1434 Assert.AreEqual (TaskStatus.RanToCompletion, t.Status, "#1");
1437 Assert.IsTrue (t.Wait (1000), "#2");
1438 Assert.AreEqual (TaskStatus.Canceled, t.Result.Status, "#3");
1442 public void WhenAny_Faulted ()
1444 var tcs = new TaskCompletionSource<object> ();
1445 tcs.SetException (new ApplicationException ());
1447 var tcs2 = new TaskCompletionSource<object> ();
1448 tcs2.SetException (new InvalidTimeZoneException ());
1450 var cancelation = new CancellationTokenSource ();
1451 var tasks = new Task[] {
1452 new Task (delegate { }),
1454 new Task (delegate { }, cancelation.Token),
1458 cancelation.Cancel ();
1460 var t = Task.WhenAny (tasks);
1461 Assert.AreEqual (TaskStatus.RanToCompletion, t.Status, "#1");
1464 Assert.IsTrue (t.Wait (1000), "#2");
1465 Assert.IsNull (t.Exception, "#3");
1467 Assert.That (t.Result.Exception.InnerException, Is.TypeOf (typeof (ApplicationException)), "#4");
1471 public void WhenAny ()
1473 var t1 = new Task (delegate { });
1474 var t2 = new Task (delegate { t1.Start (); });
1476 var tasks = new Task[] {
1481 var t = Task.WhenAny (tasks);
1482 Assert.AreEqual (TaskStatus.WaitingForActivation, t.Status, "#1");
1485 Assert.IsTrue (t.Wait (1000), "#2");
1486 Assert.IsNotNull (t.Result, "#3");
1490 public void WhenAnyResult_WithNull ()
1492 var tasks = new [] {
1493 Task.FromResult (2),
1498 Task.WhenAny<int> (tasks);
1500 } catch (ArgumentException) {
1505 Task.WhenAny<int> (tasks);
1507 } catch (ArgumentException) {
1511 Task.WhenAny<short> (new Task<short>[0]);
1513 } catch (ArgumentException) {
1518 public void WhenAnyResult_Start ()
1521 Task.FromResult (2),
1524 var t = Task.WhenAny<int> (tasks);
1525 Assert.AreEqual (TaskStatus.RanToCompletion, t.Status, "#1");
1530 } catch (InvalidOperationException) {
1534 new Task<int> (delegate { return 55; }),
1537 t = Task.WhenAny<int> (tasks);
1538 Assert.AreEqual (TaskStatus.WaitingForActivation, t.Status, "#11");
1542 Assert.Fail ("#12");
1543 } catch (InvalidOperationException) {
1548 public void WhenAnyResult_Cancelled ()
1550 var cancelation = new CancellationTokenSource ();
1551 var tasks = new [] {
1552 new Task<double> (delegate { return 1.1; }),
1553 new Task<double> (delegate { return -4.4; }, cancelation.Token)
1556 cancelation.Cancel ();
1558 var t = Task.WhenAny<double> (tasks);
1559 Assert.AreEqual (TaskStatus.RanToCompletion, t.Status, "#1");
1562 Assert.IsTrue (t.Wait (1000), "#2");
1563 Assert.AreEqual (TaskStatus.Canceled, t.Result.Status, "#3");
1567 public void WhenAnyResult_Faulted ()
1569 var tcs = new TaskCompletionSource<object> ();
1570 tcs.SetException (new ApplicationException ());
1572 var tcs2 = new TaskCompletionSource<object> ();
1573 tcs2.SetException (new InvalidTimeZoneException ());
1575 var cancelation = new CancellationTokenSource ();
1576 var tasks = new Task<object>[] {
1577 new Task<object> (delegate { return null; }),
1579 new Task<object> (delegate { return ""; }, cancelation.Token),
1583 cancelation.Cancel ();
1585 var t = Task.WhenAny<object> (tasks);
1586 Assert.AreEqual (TaskStatus.RanToCompletion, t.Status, "#1");
1589 Assert.IsTrue (t.Wait (1000), "#2");
1590 Assert.IsNull (t.Exception, "#3");
1592 Assert.That (t.Result.Exception.InnerException, Is.TypeOf (typeof (ApplicationException)), "#4");
1596 public void WhenAnyResult ()
1598 var t1 = new Task<byte> (delegate { return 3; });
1599 var t2 = new Task<byte> (delegate { t1.Start (); return 2; });
1601 var tasks = new [] {
1606 var t = Task.WhenAny<byte> (tasks);
1607 Assert.AreEqual (TaskStatus.WaitingForActivation, t.Status, "#1");
1610 Assert.IsTrue (t.Wait (1000), "#2");
1611 Assert.IsTrue (t.Result.Result > 1, "#3");
1615 public void ContinueWith_StateValue ()
1617 var t = Task.Factory.StartNew (l => {
1618 Assert.AreEqual (1, l, "a-1");
1621 var c = t.ContinueWith ((a, b) => {
1622 Assert.AreEqual (t, a, "c-1");
1623 Assert.AreEqual (2, b, "c-2");
1626 var d = t.ContinueWith ((a, b) => {
1627 Assert.AreEqual (t, a, "d-1");
1628 Assert.AreEqual (3, b, "d-2");
1632 Assert.IsTrue (d.Wait (1000), "#1");
1634 Assert.AreEqual (1, t.AsyncState, "#2");
1635 Assert.AreEqual (2, c.AsyncState, "#3");
1636 Assert.AreEqual (3, d.AsyncState, "#4");
1640 public void ContinueWith_StateValueGeneric ()
1642 var t = Task<int>.Factory.StartNew (l => {
1643 Assert.AreEqual (1, l, "a-1");
1647 var c = t.ContinueWith ((a, b) => {
1648 Assert.AreEqual (t, a, "c-1");
1649 Assert.AreEqual (2, b, "c-2");
1653 var d = t.ContinueWith ((a, b) => {
1654 Assert.AreEqual (t, a, "d-1");
1655 Assert.AreEqual (3, b, "d-2");
1659 Assert.IsTrue (d.Wait (1000), "#1");
1661 Assert.AreEqual (1, t.AsyncState, "#2");
1662 Assert.AreEqual (80, t.Result, "#2r");
1663 Assert.AreEqual (2, c.AsyncState, "#3");
1664 Assert.AreEqual ("c", c.Result, "#3r");
1665 Assert.AreEqual (3, d.AsyncState, "#4");
1666 Assert.AreEqual ('d', d.Result, "#3r");
1670 public void ContinueWith_CustomScheduleRejected ()
1672 var scheduler = new NonInlineableScheduler ();
1673 var t = Task.Factory.StartNew (delegate { }).
1674 ContinueWith (r => {}, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, scheduler);
1676 Assert.IsTrue (t.Wait (5000));
1680 public void FromResult ()
1682 var t = Task.FromResult<object> (null);
1683 Assert.IsTrue (t.IsCompleted, "#1");
1684 Assert.AreEqual (null, t.Result, "#2");
1690 public void LongRunning ()
1694 var t = new Task (() => { is_tp = Thread.CurrentThread.IsThreadPoolThread; is_bg = Thread.CurrentThread.IsBackground; });
1696 Assert.IsTrue (t.Wait (100));
1697 Assert.IsTrue ((bool)is_tp, "#1");
1698 Assert.IsTrue ((bool)is_bg, "#2");
1702 t = new Task (() => { is_tp = Thread.CurrentThread.IsThreadPoolThread; is_bg = Thread.CurrentThread.IsBackground; }, TaskCreationOptions.LongRunning);
1705 Assert.IsTrue (t.Wait (100));
1706 Assert.IsFalse ((bool) is_tp, "#11");
1707 Assert.IsTrue ((bool) is_bg, "#12");
1711 public void Run_ArgumentCheck ()
1714 Task.Run (null as Action);
1716 } catch (ArgumentNullException) {
1723 bool ranOnDefaultScheduler = false;
1724 var t = Task.Run (delegate { ranOnDefaultScheduler = Thread.CurrentThread.IsThreadPoolThread; });
1725 Assert.AreEqual (TaskCreationOptions.DenyChildAttach, t.CreationOptions, "#1");
1727 Assert.IsTrue (ranOnDefaultScheduler, "#2");
1731 public void Run_Cancel ()
1733 var t = Task.Run (() => 1, new CancellationToken (true));
1737 } catch (AggregateException) {
1740 Assert.IsTrue (t.IsCanceled, "#2");
1744 public void Run_ExistingTaskT ()
1746 var t = new Task<int> (() => 5);
1747 var t2 = Task.Run (() => { t.Start (); return t; });
1749 Assert.IsTrue (t2.Wait (1000), "#1");
1750 Assert.AreEqual (5, t2.Result, "#2");
1754 public void Run_ExistingTask ()
1756 var t = new Task (delegate { throw new Exception ("Foo"); });
1757 var t2 = Task.Run (() => { t.Start (); return t; });
1762 } catch (Exception) {}
1764 Assert.AreEqual (TaskStatus.Faulted, t.Status, "#2");
1768 public void DenyChildAttachTest ()
1770 var mre = new ManualResetEventSlim ();
1772 Task parent = Task.Factory.StartNew (() => {
1773 nested = Task.Factory.StartNew (() => mre.Wait (2000), TaskCreationOptions.AttachedToParent);
1774 }, TaskCreationOptions.DenyChildAttach);
1775 Assert.IsTrue (parent.Wait (1000), "#1");
1777 Assert.IsTrue (nested.Wait (2000), "#2");
1780 class SynchronousScheduler : TaskScheduler
1782 protected override IEnumerable<Task> GetScheduledTasks ()
1784 throw new NotImplementedException ();
1787 protected override void QueueTask (Task task)
1789 TryExecuteTaskInline (task, false);
1792 protected override bool TryExecuteTaskInline (Task task, bool taskWasPreviouslyQueued)
1794 return base.TryExecuteTask (task);
1799 public void HideSchedulerTest ()
1801 var mre = new ManualResetEventSlim ();
1802 var ranOnDefault = false;
1803 var scheduler = new SynchronousScheduler ();
1805 Task parent = Task.Factory.StartNew (() => {
1806 Task.Factory.StartNew (() => {
1807 ranOnDefault = Thread.CurrentThread.IsThreadPoolThread;
1810 }, CancellationToken.None, TaskCreationOptions.HideScheduler, scheduler);
1812 Assert.IsTrue (mre.Wait (1000), "#1");
1813 Assert.IsTrue (ranOnDefault, "#2");
1817 public void LazyCancelationTest ()
1819 var source = new CancellationTokenSource ();
1821 var parent = new Task (delegate {});
1822 var cont = parent.ContinueWith (delegate {}, source.Token, TaskContinuationOptions.LazyCancellation, TaskScheduler.Default);
1824 Assert.AreNotEqual (TaskStatus.Canceled, cont.Status, "#1");
1827 Assert.IsTrue (cont.Wait (1000), "#2");
1829 } catch (AggregateException ex) {
1830 Assert.That (ex.InnerException, Is.TypeOf (typeof (TaskCanceledException)), "#3");