Welcome to mirror list, hosted at ThFree Co, Russian Federation.

TaskAwaiterTest.cs « System.Runtime.CompilerServices « Test « corlib « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 69ba983eeac6b1c932881f239525872efeef3cec (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
//
// TaskAwaiterTest.cs
//
// Authors:
//	Marek Safar  <marek.safar@gmail.com>
//
// Copyright (C) 2011 Xamarin, Inc (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

#if NET_4_5

using System;
using System.Threading;
using System.Threading.Tasks;
using NUnit.Framework;
using System.Runtime.CompilerServices;
using System.Collections.Generic;
using System.Collections;
using System.Collections.Concurrent;

namespace MonoTests.System.Runtime.CompilerServices
{
	[TestFixture]
	public class TaskAwaiterTest
	{
		class Scheduler : TaskScheduler
		{
			string name;
			int ic, qc;

			public Scheduler (string name)
			{
				this.name = name;
			}

			public int InlineCalls { get { return ic; } }
			public int QueueCalls { get { return qc; } }

			protected override IEnumerable<Task> GetScheduledTasks ()
			{
				throw new NotImplementedException ();
			}

			protected override void QueueTask (Task task)
			{
				Interlocked.Increment (ref qc);
				ThreadPool.QueueUserWorkItem (o => {
					TryExecuteTask (task);
				});
			}

			protected override bool TryExecuteTaskInline (Task task, bool taskWasPreviouslyQueued)
			{
				Interlocked.Increment (ref ic);
				return false;
			}

			public override string ToString ()
			{
				return "Scheduler-" + name;
			}
		}

		class SingleThreadSynchronizationContext : SynchronizationContext
		{
			readonly Queue _queue = new Queue ();

			public void RunOnCurrentThread ()
			{
				while (_queue.Count != 0) {
					var workItem = (KeyValuePair<SendOrPostCallback, object>) _queue.Dequeue ();
					workItem.Key (workItem.Value);
				}
			}
				
			public override void Post (SendOrPostCallback d, object state)
			{
				if (d == null) {
					throw new ArgumentNullException ("d");
				}

				_queue.Enqueue (new KeyValuePair<SendOrPostCallback, object> (d, state));
			}

			public override void Send (SendOrPostCallback d, object state)
			{
				throw new NotSupportedException ("Synchronously sending is not supported.");
			}
		}

		class NestedSynchronizationContext : SynchronizationContext
		{
			Thread thread;
			readonly ConcurrentQueue<Tuple<SendOrPostCallback, object, ExecutionContext>> workQueue = new ConcurrentQueue<Tuple<SendOrPostCallback, object, ExecutionContext>> ();
			readonly AutoResetEvent workReady = new AutoResetEvent (false);

			public NestedSynchronizationContext ()
			{
				thread = new Thread (WorkerThreadProc) { IsBackground = true };
				thread.Start ();
			}

			public override void Post (SendOrPostCallback d, object state)
			{
				var context = ExecutionContext.Capture ();
				workQueue.Enqueue (Tuple.Create (d, state, context));
				workReady.Set ();
			}

			void WorkerThreadProc ()
			{
				if (!workReady.WaitOne (10000))
					return;

				Tuple<SendOrPostCallback, object, ExecutionContext> work;

				while (workQueue.TryDequeue (out work)) {
					ExecutionContext.Run (work.Item3, _ => {
						var oldSyncContext = SynchronizationContext.Current;
						SynchronizationContext.SetSynchronizationContext (this);
						work.Item1 (_);
						SynchronizationContext.SetSynchronizationContext (oldSyncContext);
					}, work.Item2);	
				}
			}
		}

		string progress;
		SynchronizationContext sc;
		ManualResetEvent mre;

		[SetUp]
		public void Setup ()
		{
			sc = SynchronizationContext.Current;
		}

		[TearDown]
		public void TearDown ()
		{
			SynchronizationContext.SetSynchronizationContext (sc);
		}

		[Test]
		public void GetResultFaulted ()
		{
			TaskAwaiter awaiter;

			var task = new Task (() => { throw new ApplicationException (); });
			awaiter = task.GetAwaiter ();
			task.RunSynchronously (TaskScheduler.Current);


			Assert.IsTrue (awaiter.IsCompleted);

			try {
				awaiter.GetResult ();
				Assert.Fail ();
			} catch (ApplicationException) {
			}
		}

		[Test]
		public void GetResultCanceled ()
		{
			TaskAwaiter awaiter;

			var token = new CancellationToken (true);
			var task = new Task (() => { }, token);
			awaiter = task.GetAwaiter ();

			try {
				awaiter.GetResult ();
				Assert.Fail ();
			} catch (TaskCanceledException) {
			}
		}

		[Test]
		public void GetResultWaitOnCompletion ()
		{
			TaskAwaiter awaiter;
				
			var task = Task.Delay (30);
			awaiter = task.GetAwaiter ();
				
			awaiter.GetResult ();
			Assert.AreEqual (TaskStatus.RanToCompletion, task.Status);
		}

		[Test]
		public void CustomScheduler ()
		{
			// some test runners (e.g. Touch.Unit) will execute this on the main thread and that would lock them
			if (!Thread.CurrentThread.IsBackground)
				Assert.Ignore ("Current thread is not running in the background.");

			var a = new Scheduler ("a");
			var b = new Scheduler ("b");

			var t = TestCS (a, b);
			Assert.IsTrue (t.Wait (3000), "#0");
			Assert.AreEqual (0, t.Result, "#1");
			Assert.AreEqual (0, b.InlineCalls, "#2b");
			Assert.IsTrue (a.QueueCalls == 1 || a.QueueCalls == 2, "#3a");
			Assert.AreEqual (1, b.QueueCalls, "#3b");
		}

		static async Task<int> TestCS (TaskScheduler schedulerA, TaskScheduler schedulerB)
		{
			var res = await Task.Factory.StartNew (async () => {
				if (TaskScheduler.Current != schedulerA)
					return 1;

				await Task.Factory.StartNew (
					() => {
						if (TaskScheduler.Current != schedulerB)
							return 2;

						return 0;
					}, CancellationToken.None, TaskCreationOptions.None, schedulerB);

				if (TaskScheduler.Current != schedulerA)
					return 3;

				return 0;
			}, CancellationToken.None, TaskCreationOptions.None, schedulerA);

			return res.Result;
		}

		[Test]
		public void FinishedTaskOnCompleted ()
		{
			var mres = new ManualResetEvent (false);
			var mres2 = new ManualResetEvent (false);

			var tcs = new TaskCompletionSource<object> ();
			tcs.SetResult (null);
			var task = tcs.Task;

			var awaiter = task.GetAwaiter ();
			Assert.IsTrue (awaiter.IsCompleted, "#1");

			awaiter.OnCompleted(() => { 
				if (mres.WaitOne (1000))
					mres2.Set ();
			});

			mres.Set ();
			// this will only terminate correctly if the test was not executed from the main thread
			// e.g. Touch.Unit defaults to run tests on the main thread and this will return false
			Assert.AreEqual (Thread.CurrentThread.IsBackground, mres2.WaitOne (2000), "#2");;
		}

		[Test]
		public void CompletionOnSameCustomSynchronizationContext ()
		{
			progress = "";
			var syncContext = new SingleThreadSynchronizationContext ();
			SynchronizationContext.SetSynchronizationContext (syncContext);

			syncContext.Post (delegate {
				Go (syncContext);
			}, null);

			// Custom message loop
			var cts = new CancellationTokenSource ();
			cts.CancelAfter (5000);
			while (progress.Length != 3 && !cts.IsCancellationRequested) {
				syncContext.RunOnCurrentThread ();
				Thread.Sleep (0);
			}

			Assert.AreEqual ("123", progress);
		}

		async void Go (SynchronizationContext ctx)
		{
			await Wait (ctx);

			progress += "2";
		}

		async Task Wait (SynchronizationContext ctx)
		{
			await Task.Delay (10); // Force block suspend/return

			ctx.Post (l => progress += "3", null);

			progress += "1";

			// Exiting same context - no need to post continuation
		}

		[Test]
		public void CompletionOnDifferentCustomSynchronizationContext ()
		{
			mre = new ManualResetEvent (false);
			progress = "";
			var syncContext = new SingleThreadSynchronizationContext ();
			SynchronizationContext.SetSynchronizationContext (syncContext);

			syncContext.Post (delegate {
				Task t = new Task (delegate() { });
				Go2 (syncContext, t);
				t.Start ();
			}, null);

			// Custom message loop
			var cts = new CancellationTokenSource ();
			cts.CancelAfter (5000);
			while (progress.Length != 3 && !cts.IsCancellationRequested) {
				syncContext.RunOnCurrentThread ();
				Thread.Sleep (0);
			}

			Assert.AreEqual ("13xa2", progress);
		}

		async void Go2 (SynchronizationContext ctx, Task t)
		{
			await Wait2 (ctx, t);

			progress += "a";

			if (mre.WaitOne (5000))
				progress += "2";
			else
				progress += "b";
		}

		async Task Wait2 (SynchronizationContext ctx, Task t)
		{
			await t; // Force block suspend/return

			ctx.Post (l => {
				progress += "3";
				mre.Set ();
				progress += "x";
			}, null);

			progress += "1";

			SynchronizationContext.SetSynchronizationContext (null);
		}

		[Test]
		public void NestedLeakingSynchronizationContext ()
		{
			var sc = SynchronizationContext.Current;
			if (sc == null)
				Assert.IsTrue (NestedLeakingSynchronizationContext_MainAsync (sc).Wait (5000), "#1");
			else
				Assert.Ignore ("NestedSynchronizationContext may never complete on custom context");
		}

		static async Task NestedLeakingSynchronizationContext_MainAsync (SynchronizationContext sc)
		{
			Assert.AreSame (sc, SynchronizationContext.Current, "#1");
			await NestedLeakingSynchronizationContext_DoWorkAsync ();
			Assert.AreSame (sc, SynchronizationContext.Current, "#2");
		}

		static async Task NestedLeakingSynchronizationContext_DoWorkAsync ()
		{
			var sc = new NestedSynchronizationContext ();
			SynchronizationContext.SetSynchronizationContext (sc);

			Assert.AreSame (sc, SynchronizationContext.Current);
			await Task.Yield ();
			Assert.AreSame (sc, SynchronizationContext.Current);
		}
	}
}

#endif