1 // TaskSchedulerTest.cs
3 // Copyright (c) 2008 Jérémie "Garuma" Laval
5 // Permission is hereby granted, free of charge, to any person obtaining a copy
6 // of this software and associated documentation files (the "Software"), to deal
7 // in the Software without restriction, including without limitation the rights
8 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 // copies of the Software, and to permit persons to whom the Software is
10 // furnished to do so, subject to the following conditions:
12 // The above copyright notice and this permission notice shall be included in
13 // all copies or substantial portions of the Software.
15 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
28 using System.Threading;
29 using System.Threading.Tasks;
30 using System.Collections.Generic;
32 using NUnit.Framework;
34 using NUnit.Framework.SyntaxHelpers;
37 namespace MonoTests.System.Threading.Tasks
40 public class TaskSchedulerTests
42 class LazyCatScheduler : TaskScheduler
44 public TaskStatus ExecuteInlineStatus
50 protected override void QueueTask (Task task)
52 throw new NotImplementedException ();
55 protected override bool TryDequeue (Task task)
57 throw new NotImplementedException ();
60 protected override bool TryExecuteTaskInline (Task task, bool taskWasPreviouslyQueued)
62 ExecuteInlineStatus = task.Status;
66 protected override IEnumerable<Task> GetScheduledTasks ()
68 throw new NotImplementedException ();
72 class DefaultScheduler : TaskScheduler
74 protected override IEnumerable<Task> GetScheduledTasks ()
76 throw new NotImplementedException ();
79 protected override void QueueTask (Task task)
81 throw new NotImplementedException ();
84 protected override bool TryExecuteTaskInline (Task task, bool taskWasPreviouslyQueued)
86 throw new NotImplementedException ();
89 public void TestDefaultMethod ()
91 Assert.IsFalse (TryDequeue (null), "#1");
96 public void FromCurrentSynchronizationContextTest_Invalid()
98 var c = SynchronizationContext.Current;
100 SynchronizationContext.SetSynchronizationContext (null);
101 TaskScheduler.FromCurrentSynchronizationContext ();
103 } catch (InvalidOperationException) {
105 SynchronizationContext.SetSynchronizationContext (c);
110 public void BasicRunSynchronouslyTest ()
113 var t = new Task (() => ran = true);
115 t.RunSynchronously ();
116 Assert.IsTrue (t.IsCompleted);
117 Assert.IsFalse (t.IsFaulted);
118 Assert.IsFalse (t.IsCanceled);
123 public void RunSynchronouslyButNoExecutionTest ()
125 TaskSchedulerException ex = null;
127 var ts = new LazyCatScheduler ();
128 Task t = new Task (() => {});
131 t.RunSynchronously (ts);
132 } catch (TaskSchedulerException e) {
136 Assert.IsNotNull (ex);
137 Assert.IsNotNull (ex.InnerException);
138 Assert.That (ex.InnerException, Is.TypeOf (typeof (InvalidOperationException)));
142 public void RunSynchronouslyTaskStatusTest ()
144 var ts = new LazyCatScheduler ();
145 var t = new Task (() => { });
148 t.RunSynchronously (ts);
150 Assert.AreEqual (TaskStatus.WaitingToRun, ts.ExecuteInlineStatus);
153 static int finalizerThreadId = -1;
155 class FinalizerCatcher
159 finalizerThreadId = Thread.CurrentThread.ManagedThreadId;
164 public void DefaultBehaviourTest ()
166 var s = new DefaultScheduler ();
167 s.TestDefaultMethod ();
170 // This test doesn't work if the GC uses multiple finalizer thread.
171 // For now it's fine since only one thread is used
173 // Depends on objects getting GCd plus installs an EH handler which catches
174 // exceptions thrown by other tasks
175 [Category ("NotWorking")]
176 public void UnobservedTaskExceptionOnFinalizerThreadTest ()
178 var foo = new FinalizerCatcher ();
181 GC.WaitForPendingFinalizers ();
182 // Same than following test, if GC didn't run don't execute the rest of this test
183 if (finalizerThreadId == -1)
186 int evtThreadId = -2;
187 TaskScheduler.UnobservedTaskException += delegate {
188 evtThreadId = Thread.CurrentThread.ManagedThreadId;
190 var evt = new ManualResetEventSlim ();
191 CreateAndForgetFaultedTask (evt);
195 GC.WaitForPendingFinalizers ();
196 Assert.AreEqual (finalizerThreadId, evtThreadId, "Should be ran on finalizer thread");
200 // Depends on objects getting GCd plus installs an EH handler which catches
201 // exceptions thrown by other tasks
202 [Category ("NotWorking")]
203 public void UnobservedTaskExceptionArgumentTest ()
206 bool senderIsRight = false;
207 UnobservedTaskExceptionEventArgs args = null;
209 TaskScheduler.UnobservedTaskException += (o, a) => {
210 senderIsRight = o.GetType ().ToString () == "System.Threading.Tasks.Task";
215 var evt = new ManualResetEventSlim ();
216 CreateAndForgetFaultedTask (evt);
220 GC.WaitForPendingFinalizers ();
222 // GC is too unreliable for some reason in that test, so backoff if finalizer wasn't ran
223 // it needs to be run for the above test to work though (♥)
227 Assert.IsNotNull (args.Exception);
228 Assert.IsNotNull (args.Exception.InnerException);
229 Assert.AreEqual ("foo", args.Exception.InnerException.Message);
230 Assert.IsFalse (args.Observed);
231 Assert.IsTrue (senderIsRight, "Sender is a task");
234 // We use this intermediary method to improve chances of GC kicking
235 static void CreateAndForgetFaultedTask (ManualResetEventSlim evt)
237 Task.Factory.StartNew (() => { evt.Set (); throw new Exception ("foo"); });