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
27 using System.Threading;
28 using System.Threading.Tasks;
29 using System.Collections.Generic;
31 using NUnit.Framework;
33 namespace MonoTests.System.Threading.Tasks
36 public class TaskSchedulerTests
38 class LazyCatScheduler : TaskScheduler
40 public TaskStatus ExecuteInlineStatus
46 protected override void QueueTask (Task task)
48 throw new NotImplementedException ();
51 protected override bool TryDequeue (Task task)
53 throw new NotImplementedException ();
56 protected override bool TryExecuteTaskInline (Task task, bool taskWasPreviouslyQueued)
58 ExecuteInlineStatus = task.Status;
62 protected override IEnumerable<Task> GetScheduledTasks ()
64 throw new NotImplementedException ();
68 class DefaultScheduler : TaskScheduler
70 protected override IEnumerable<Task> GetScheduledTasks ()
72 throw new NotImplementedException ();
75 protected override void QueueTask (Task task)
77 throw new NotImplementedException ();
80 protected override bool TryExecuteTaskInline (Task task, bool taskWasPreviouslyQueued)
82 throw new NotImplementedException ();
85 public void TestDefaultMethod ()
87 Assert.IsFalse (TryDequeue (null), "#1");
91 class UserSynchronizationContext : SynchronizationContext
97 public void FromCurrentSynchronizationContextTest_Invalid()
99 var c = SynchronizationContext.Current;
101 SynchronizationContext.SetSynchronizationContext (null);
102 TaskScheduler.FromCurrentSynchronizationContext ();
104 } catch (InvalidOperationException) {
106 SynchronizationContext.SetSynchronizationContext (c);
111 public void FromUserSynchronizationContext ()
113 var c = SynchronizationContext.Current;
115 SynchronizationContext.SetSynchronizationContext (new UserSynchronizationContext ());
116 var ts = TaskScheduler.FromCurrentSynchronizationContext ();
117 Assert.AreEqual (1, ts.MaximumConcurrencyLevel, "#1");
119 SynchronizationContext.SetSynchronizationContext (c);
124 public void BasicRunSynchronouslyTest ()
127 var t = new Task (() => ran = true);
129 t.RunSynchronously ();
130 Assert.IsTrue (t.IsCompleted);
131 Assert.IsFalse (t.IsFaulted);
132 Assert.IsFalse (t.IsCanceled);
137 public void RunSynchronouslyButNoExecutionTest ()
139 TaskSchedulerException ex = null;
141 var ts = new LazyCatScheduler ();
142 Task t = new Task (() => {});
145 t.RunSynchronously (ts);
146 } catch (TaskSchedulerException e) {
150 Assert.IsNotNull (ex);
151 Assert.IsNotNull (ex.InnerException);
152 Assert.That (ex.InnerException, Is.TypeOf (typeof (InvalidOperationException)));
156 public void RunSynchronouslyTaskStatusTest ()
158 var ts = new LazyCatScheduler ();
159 var t = new Task (() => { });
162 t.RunSynchronously (ts);
164 Assert.AreEqual (TaskStatus.WaitingToRun, ts.ExecuteInlineStatus);
167 static int finalizerThreadId = -1;
169 class FinalizerCatcher
173 finalizerThreadId = Thread.CurrentThread.ManagedThreadId;
178 public void DefaultBehaviourTest ()
180 var s = new DefaultScheduler ();
181 s.TestDefaultMethod ();
184 // This test doesn't work if the GC uses multiple finalizer thread.
185 // For now it's fine since only one thread is used
187 // Depends on objects getting GCd plus installs an EH handler which catches
188 // exceptions thrown by other tasks
189 [Category ("NotWorking")]
190 public void UnobservedTaskExceptionOnFinalizerThreadTest ()
192 var foo = new FinalizerCatcher ();
195 GC.WaitForPendingFinalizers ();
196 // Same than following test, if GC didn't run don't execute the rest of this test
197 if (finalizerThreadId == -1)
200 int evtThreadId = -2;
201 TaskScheduler.UnobservedTaskException += delegate {
202 evtThreadId = Thread.CurrentThread.ManagedThreadId;
204 var evt = new ManualResetEventSlim ();
205 CreateAndForgetFaultedTask (evt);
209 GC.WaitForPendingFinalizers ();
210 Assert.AreEqual (finalizerThreadId, evtThreadId, "Should be ran on finalizer thread");
214 // Depends on objects getting GCd plus installs an EH handler which catches
215 // exceptions thrown by other tasks
216 [Category ("NotWorking")]
217 public void UnobservedTaskExceptionArgumentTest ()
220 bool senderIsRight = false;
221 UnobservedTaskExceptionEventArgs args = null;
223 TaskScheduler.UnobservedTaskException += (o, a) => {
224 senderIsRight = o.GetType ().ToString () == "System.Threading.Tasks.Task";
229 var evt = new ManualResetEventSlim ();
230 CreateAndForgetFaultedTask (evt);
234 GC.WaitForPendingFinalizers ();
236 // GC is too unreliable for some reason in that test, so backoff if finalizer wasn't ran
237 // it needs to be run for the above test to work though (♥)
241 Assert.IsNotNull (args.Exception);
242 Assert.IsNotNull (args.Exception.InnerException);
243 Assert.AreEqual ("foo", args.Exception.InnerException.Message);
244 Assert.IsFalse (args.Observed);
245 Assert.IsTrue (senderIsRight, "Sender is a task");
248 // We use this intermediary method to improve chances of GC kicking
249 static void CreateAndForgetFaultedTask (ManualResetEventSlim evt)
251 Task.Factory.StartNew (() => { evt.Set (); throw new Exception ("foo"); });