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;
39 namespace MonoTests.System.Runtime.CompilerServices
42 public class TaskAwaiterTest
44 class Scheduler : TaskScheduler
49 public Scheduler (string name)
54 public int InlineCalls { get { return ic; } }
55 public int QueueCalls { get { return qc; } }
57 protected override IEnumerable<Task> GetScheduledTasks ()
59 throw new NotImplementedException ();
62 protected override void QueueTask (Task task)
64 Interlocked.Increment (ref qc);
65 ThreadPool.QueueUserWorkItem (o => {
66 TryExecuteTask (task);
70 protected override bool TryExecuteTaskInline (Task task, bool taskWasPreviouslyQueued)
72 Interlocked.Increment (ref ic);
76 public override string ToString ()
78 return "Scheduler-" + name;
82 class SingleThreadSynchronizationContext : SynchronizationContext
84 readonly Queue _queue = new Queue ();
86 public void RunOnCurrentThread ()
88 while (_queue.Count != 0) {
89 var workItem = (KeyValuePair<SendOrPostCallback, object>) _queue.Dequeue ();
90 workItem.Key (workItem.Value);
94 public override void Post (SendOrPostCallback d, object state)
97 throw new ArgumentNullException ("d");
100 _queue.Enqueue (new KeyValuePair<SendOrPostCallback, object> (d, state));
103 public override void Send (SendOrPostCallback d, object state)
105 throw new NotSupportedException ("Synchronously sending is not supported.");
110 SynchronizationContext sc;
111 ManualResetEvent mre;
116 sc = SynchronizationContext.Current;
120 public void TearDown ()
122 SynchronizationContext.SetSynchronizationContext (sc);
126 public void GetResultFaulted ()
130 var task = new Task (() => { throw new ApplicationException (); });
131 awaiter = task.GetAwaiter ();
132 task.RunSynchronously (TaskScheduler.Current);
135 Assert.IsTrue (awaiter.IsCompleted);
138 awaiter.GetResult ();
140 } catch (ApplicationException) {
145 public void GetResultCanceled ()
149 var token = new CancellationToken (true);
150 var task = new Task (() => { }, token);
151 awaiter = task.GetAwaiter ();
154 awaiter.GetResult ();
156 } catch (TaskCanceledException) {
161 public void GetResultWaitOnCompletion ()
165 var task = Task.Delay (30);
166 awaiter = task.GetAwaiter ();
168 awaiter.GetResult ();
169 Assert.AreEqual (TaskStatus.RanToCompletion, task.Status);
173 public void CustomScheduler ()
175 // some test runners (e.g. Touch.Unit) will execute this on the main thread and that would lock them
176 if (!Thread.CurrentThread.IsBackground)
177 Assert.Ignore ("Current thread is not running in the background.");
179 var a = new Scheduler ("a");
180 var b = new Scheduler ("b");
182 var t = TestCS (a, b);
183 Assert.IsTrue (t.Wait (3000), "#0");
184 Assert.AreEqual (0, t.Result, "#1");
185 Assert.AreEqual (0, b.InlineCalls, "#2b");
186 Assert.IsTrue (a.QueueCalls == 1 || a.QueueCalls == 2, "#3a");
187 Assert.AreEqual (1, b.QueueCalls, "#3b");
190 static async Task<int> TestCS (TaskScheduler schedulerA, TaskScheduler schedulerB)
192 var res = await Task.Factory.StartNew (async () => {
193 if (TaskScheduler.Current != schedulerA)
196 await Task.Factory.StartNew (
198 if (TaskScheduler.Current != schedulerB)
202 }, CancellationToken.None, TaskCreationOptions.None, schedulerB);
204 if (TaskScheduler.Current != schedulerA)
208 }, CancellationToken.None, TaskCreationOptions.None, schedulerA);
214 public void FinishedTaskOnCompleted ()
216 var mres = new ManualResetEvent (false);
217 var mres2 = new ManualResetEvent (false);
219 var tcs = new TaskCompletionSource<object> ();
220 tcs.SetResult (null);
223 var awaiter = task.GetAwaiter ();
224 Assert.IsTrue (awaiter.IsCompleted, "#1");
226 awaiter.OnCompleted(() => {
227 if (mres.WaitOne (1000))
232 // this will only terminate correctly if the test was not executed from the main thread
233 // e.g. Touch.Unit defaults to run tests on the main thread and this will return false
234 Assert.AreEqual (Thread.CurrentThread.IsBackground, mres2.WaitOne (2000), "#2");;
238 public void CompletionOnSameCustomSynchronizationContext ()
241 var syncContext = new SingleThreadSynchronizationContext ();
242 SynchronizationContext.SetSynchronizationContext (syncContext);
244 syncContext.Post (delegate {
248 // Custom message loop
249 var cts = new CancellationTokenSource ();
250 cts.CancelAfter (5000);
251 while (progress.Length != 3 && !cts.IsCancellationRequested) {
252 syncContext.RunOnCurrentThread ();
256 Assert.AreEqual ("123", progress);
259 async void Go (SynchronizationContext ctx)
266 async Task Wait (SynchronizationContext ctx)
268 await Task.Delay (10); // Force block suspend/return
270 ctx.Post (l => progress += "3", null);
274 // Exiting same context - no need to post continuation
278 public void CompletionOnDifferentCustomSynchronizationContext ()
280 mre = new ManualResetEvent (false);
282 var syncContext = new SingleThreadSynchronizationContext ();
283 SynchronizationContext.SetSynchronizationContext (syncContext);
285 syncContext.Post (delegate {
286 Task t = new Task (delegate() { });
287 Go2 (syncContext, t);
291 // Custom message loop
292 var cts = new CancellationTokenSource ();
293 cts.CancelAfter (5000);
294 while (progress.Length != 3 && !cts.IsCancellationRequested) {
295 syncContext.RunOnCurrentThread ();
299 Assert.AreEqual ("13xa2", progress);
302 async void Go2 (SynchronizationContext ctx, Task t)
304 await Wait2 (ctx, t);
308 if (mre.WaitOne (5000))
314 async Task Wait2 (SynchronizationContext ctx, Task t)
316 await t; // Force block suspend/return
326 SynchronizationContext.SetSynchronizationContext (null);