5 // Marek Safar <marek.safar@gmail.com>
7 // Copyright (C) 2011 Xamarin, Inc (http://www.xamarin.com)
9 // Permission is hereby granted, free of charge, to any person obtaining
10 // a copy of this software and associated documentation files (the
11 // "Software"), to deal in the Software without restriction, including
12 // without limitation the rights to use, copy, modify, merge, publish,
13 // distribute, sublicense, and/or sell copies of the Software, and to
14 // permit persons to whom the Software is furnished to do so, subject to
15 // the following conditions:
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
20 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
24 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
32 using System.Threading;
33 using System.Threading.Tasks;
34 using NUnit.Framework;
35 using System.Runtime.CompilerServices;
36 using System.Collections.Generic;
37 using System.Collections;
38 using System.Collections.Concurrent;
40 namespace MonoTests.System.Runtime.CompilerServices
43 public class TaskAwaiterTest
45 class Scheduler : TaskScheduler
50 public Scheduler (string name)
55 public int InlineCalls { get { return ic; } }
56 public int QueueCalls { get { return qc; } }
58 protected override IEnumerable<Task> GetScheduledTasks ()
60 throw new NotImplementedException ();
63 protected override void QueueTask (Task task)
65 Interlocked.Increment (ref qc);
66 ThreadPool.QueueUserWorkItem (o => {
67 TryExecuteTask (task);
71 protected override bool TryExecuteTaskInline (Task task, bool taskWasPreviouslyQueued)
73 Interlocked.Increment (ref ic);
77 public override string ToString ()
79 return "Scheduler-" + name;
83 class SingleThreadSynchronizationContext : SynchronizationContext
85 readonly Queue _queue = new Queue ();
87 public void RunOnCurrentThread ()
89 while (_queue.Count != 0) {
90 var workItem = (KeyValuePair<SendOrPostCallback, object>) _queue.Dequeue ();
91 workItem.Key (workItem.Value);
95 public override void Post (SendOrPostCallback d, object state)
98 throw new ArgumentNullException ("d");
101 _queue.Enqueue (new KeyValuePair<SendOrPostCallback, object> (d, state));
104 public override void Send (SendOrPostCallback d, object state)
106 throw new NotSupportedException ("Synchronously sending is not supported.");
110 class NestedSynchronizationContext : SynchronizationContext
113 readonly ConcurrentQueue<Tuple<SendOrPostCallback, object, ExecutionContext>> workQueue = new ConcurrentQueue<Tuple<SendOrPostCallback, object, ExecutionContext>> ();
114 readonly AutoResetEvent workReady = new AutoResetEvent (false);
116 public NestedSynchronizationContext ()
118 thread = new Thread (WorkerThreadProc) { IsBackground = true };
122 public override void Post (SendOrPostCallback d, object state)
124 var context = ExecutionContext.Capture ();
125 workQueue.Enqueue (Tuple.Create (d, state, context));
129 void WorkerThreadProc ()
131 if (!workReady.WaitOne (10000))
134 Tuple<SendOrPostCallback, object, ExecutionContext> work;
136 while (workQueue.TryDequeue (out work)) {
137 ExecutionContext.Run (work.Item3, _ => {
138 var oldSyncContext = SynchronizationContext.Current;
139 SynchronizationContext.SetSynchronizationContext (this);
141 SynchronizationContext.SetSynchronizationContext (oldSyncContext);
148 SynchronizationContext sc;
149 ManualResetEvent mre;
154 sc = SynchronizationContext.Current;
158 public void TearDown ()
160 SynchronizationContext.SetSynchronizationContext (sc);
164 public void GetResultFaulted ()
168 var task = new Task (() => { throw new ApplicationException (); });
169 awaiter = task.GetAwaiter ();
170 task.RunSynchronously (TaskScheduler.Current);
173 Assert.IsTrue (awaiter.IsCompleted);
176 awaiter.GetResult ();
178 } catch (ApplicationException) {
183 public void GetResultCanceled ()
187 var token = new CancellationToken (true);
188 var task = new Task (() => { }, token);
189 awaiter = task.GetAwaiter ();
192 awaiter.GetResult ();
194 } catch (TaskCanceledException) {
199 public void GetResultWaitOnCompletion ()
203 var task = Task.Delay (30);
204 awaiter = task.GetAwaiter ();
206 awaiter.GetResult ();
207 Assert.AreEqual (TaskStatus.RanToCompletion, task.Status);
211 public void CustomScheduler ()
213 // some test runners (e.g. Touch.Unit) will execute this on the main thread and that would lock them
214 if (!Thread.CurrentThread.IsBackground)
215 Assert.Ignore ("Current thread is not running in the background.");
217 var a = new Scheduler ("a");
218 var b = new Scheduler ("b");
220 var t = TestCS (a, b);
221 Assert.IsTrue (t.Wait (3000), "#0");
222 Assert.AreEqual (0, t.Result, "#1");
223 Assert.AreEqual (0, b.InlineCalls, "#2b");
224 Assert.IsTrue (a.QueueCalls == 1 || a.QueueCalls == 2, "#3a");
225 Assert.AreEqual (1, b.QueueCalls, "#3b");
228 static async Task<int> TestCS (TaskScheduler schedulerA, TaskScheduler schedulerB)
230 var res = await Task.Factory.StartNew (async () => {
231 if (TaskScheduler.Current != schedulerA)
234 await Task.Factory.StartNew (
236 if (TaskScheduler.Current != schedulerB)
240 }, CancellationToken.None, TaskCreationOptions.None, schedulerB);
242 if (TaskScheduler.Current != schedulerA)
246 }, CancellationToken.None, TaskCreationOptions.None, schedulerA);
252 public void FinishedTaskOnCompleted ()
254 var mres = new ManualResetEvent (false);
255 var mres2 = new ManualResetEvent (false);
257 var tcs = new TaskCompletionSource<object> ();
258 tcs.SetResult (null);
261 var awaiter = task.GetAwaiter ();
262 Assert.IsTrue (awaiter.IsCompleted, "#1");
264 awaiter.OnCompleted(() => {
265 if (mres.WaitOne (1000))
270 // this will only terminate correctly if the test was not executed from the main thread
271 // e.g. Touch.Unit defaults to run tests on the main thread and this will return false
272 Assert.AreEqual (Thread.CurrentThread.IsBackground, mres2.WaitOne (2000), "#2");;
276 public void CompletionOnSameCustomSynchronizationContext ()
279 var syncContext = new SingleThreadSynchronizationContext ();
280 SynchronizationContext.SetSynchronizationContext (syncContext);
282 syncContext.Post (delegate {
286 // Custom message loop
287 var cts = new CancellationTokenSource ();
288 cts.CancelAfter (5000);
289 while (progress.Length != 3 && !cts.IsCancellationRequested) {
290 syncContext.RunOnCurrentThread ();
294 Assert.AreEqual ("123", progress);
297 async void Go (SynchronizationContext ctx)
304 async Task Wait (SynchronizationContext ctx)
306 await Task.Delay (10); // Force block suspend/return
308 ctx.Post (l => progress += "3", null);
312 // Exiting same context - no need to post continuation
316 public void CompletionOnDifferentCustomSynchronizationContext ()
318 mre = new ManualResetEvent (false);
320 var syncContext = new SingleThreadSynchronizationContext ();
321 SynchronizationContext.SetSynchronizationContext (syncContext);
323 syncContext.Post (delegate {
324 Task t = new Task (delegate() { });
325 Go2 (syncContext, t);
329 // Custom message loop
330 var cts = new CancellationTokenSource ();
331 cts.CancelAfter (5000);
332 while (progress.Length != 3 && !cts.IsCancellationRequested) {
333 syncContext.RunOnCurrentThread ();
337 Assert.AreEqual ("13xa2", progress);
340 async void Go2 (SynchronizationContext ctx, Task t)
342 await Wait2 (ctx, t);
346 if (mre.WaitOne (5000))
352 async Task Wait2 (SynchronizationContext ctx, Task t)
354 await t; // Force block suspend/return
364 SynchronizationContext.SetSynchronizationContext (null);
368 public void NestedLeakingSynchronizationContext ()
370 var sc = SynchronizationContext.Current;
371 Assert.IsTrue (NestedLeakingSynchronizationContext_MainAsync (sc).Wait (5000), "#1");
374 static async Task NestedLeakingSynchronizationContext_MainAsync (SynchronizationContext sc)
376 Assert.AreSame (sc, SynchronizationContext.Current, "#1");
377 await NestedLeakingSynchronizationContext_DoWorkAsync ();
378 Assert.AreSame (sc, SynchronizationContext.Current, "#2");
381 static async Task NestedLeakingSynchronizationContext_DoWorkAsync ()
383 var sc = new NestedSynchronizationContext ();
384 SynchronizationContext.SetSynchronizationContext (sc);
386 Assert.AreSame (sc, SynchronizationContext.Current);
388 Assert.AreSame (sc, SynchronizationContext.Current);