5 // Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
6 // Marek Safar <marek.safar@gmail.com>
8 // Copyright (c) 2010 Jérémie "Garuma" Laval
9 // Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
11 // Permission is hereby granted, free of charge, to any person obtaining a copy
12 // of this software and associated documentation files (the "Software"), to deal
13 // in the Software without restriction, including without limitation the rights
14 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15 // copies of the Software, and to permit persons to whom the Software is
16 // furnished to do so, subject to the following conditions:
18 // The above copyright notice and this permission notice shall be included in
19 // all copies or substantial portions of the Software.
21 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
34 using System.Threading;
35 using System.Threading.Tasks;
36 using System.Collections.Generic;
38 using NUnit.Framework;
40 namespace MonoTests.System.Threading.Tasks
43 public class TaskFactoryTests
45 class CompletedAsyncResult : IAsyncResult
47 public object AsyncState
49 get { throw new NotImplementedException (); }
52 public WaitHandle AsyncWaitHandle
54 get { throw new NotImplementedException (); }
57 public bool CompletedSynchronously
59 get { throw new NotImplementedException (); }
62 public bool IsCompleted
68 class TestAsyncResult : IAsyncResult
70 WaitHandle wh = new ManualResetEvent (true);
72 public object AsyncState
74 get { throw new NotImplementedException (); }
77 public WaitHandle AsyncWaitHandle
85 public bool CompletedSynchronously
87 get { throw new NotImplementedException (); }
90 public bool IsCompleted
96 class TestScheduler : TaskScheduler
98 public bool ExecutedInline { get; set; }
100 protected override void QueueTask (Task task)
102 throw new NotImplementedException ();
105 protected override bool TryDequeue (Task task)
107 throw new NotImplementedException ();
110 protected override bool TryExecuteTaskInline (Task task, bool taskWasPreviouslyQueued)
112 if (taskWasPreviouslyQueued)
113 throw new ArgumentException ("taskWasPreviouslyQueued");
115 if (task.Status != TaskStatus.WaitingToRun)
116 throw new ArgumentException ("task.Status");
118 ExecutedInline = true;
119 return TryExecuteTask (task);
122 protected override IEnumerable<Task> GetScheduledTasks ()
124 throw new NotImplementedException ();
134 this.factory = Task.Factory;
138 public void StartNewTest ()
141 factory.StartNew (() => result = true).Wait ();
142 Assert.IsTrue (result);
146 public void NoDefaultScheduler ()
148 Assert.IsNull (factory.Scheduler, "#1");
152 public void ContinueWhenAllTest ()
154 bool r1 = false, r2 = false, r3 = false;
156 Task[] tasks = new Task[3];
157 tasks[0] = new Task (() => { Thread.Sleep (100); r1 = true; });
158 tasks[1] = new Task (() => { Thread.Sleep (500); r2 = true; });
159 tasks[2] = new Task (() => { Thread.Sleep (300); r3 = true; });
163 Task cont = factory.ContinueWhenAll (tasks, (ts) => { if (r1 && r2 && r3) result = true; });
165 foreach (Task t in tasks)
168 Assert.IsTrue (cont.Wait (1000), "#0");
170 Assert.IsTrue (r1, "#1");
171 Assert.IsTrue (r2, "#2");
172 Assert.IsTrue (r3, "#3");
173 Assert.IsTrue (result, "#4");
177 public void ContinueWhenAnyTest ()
179 bool r = false, result = false, finished = false;
181 Task[] tasks = new Task[2];
182 tasks[0] = new Task (() => { Thread.Sleep (300); r = true; });
183 tasks[1] = new Task (() => { SpinWait sw = new SpinWait (); while (!finished) sw.SpinOnce (); });
184 //tasks[2] = new Task (() => { SpinWait sw; while (!finished) sw.SpinOnce (); });
186 Task cont = factory.ContinueWhenAny (tasks, (t) => { if (r) result = t == tasks[0]; finished = true; });
188 foreach (Task t in tasks)
191 Assert.IsTrue (cont.Wait (2000), "#0");
193 Assert.IsTrue (r, "#1");
194 Assert.IsTrue (result, "#2");
195 Assert.IsTrue (finished, "#3");
199 public void FromAsyncBeginInvoke_WithResult ()
203 Func<int, int> func = (i) => {
204 Assert.IsTrue (Thread.CurrentThread.IsThreadPoolThread);
205 result = true; return i + 3;
208 var task = factory.FromAsync<int, int> (func.BeginInvoke, func.EndInvoke, 1, "state", TaskCreationOptions.AttachedToParent);
209 Assert.IsTrue (task.Wait (5000), "#1");
210 Assert.IsTrue (result, "#2");
211 Assert.AreEqual (4, task.Result, "#3");
212 Assert.AreEqual ("state", (string) task.AsyncState, "#4");
213 Assert.AreEqual (TaskCreationOptions.AttachedToParent, task.CreationOptions, "#5");
217 public void FromAsyncBeginMethod_DirectResult ()
220 bool continuationTest = false;
222 Func<int, int> func = (i) => { result = true; return i + 3; };
223 Task<int> task = factory.FromAsync<int> (func.BeginInvoke (1, delegate { }, null), func.EndInvoke);
224 var cont = task.ContinueWith (_ => continuationTest = true, TaskContinuationOptions.ExecuteSynchronously);
228 Assert.IsTrue (result);
229 Assert.IsTrue (continuationTest);
230 Assert.AreEqual (4, task.Result);
234 public void FromAsyncBeginMethod_Exception ()
237 bool continuationTest = false;
239 Func<int, int> func = (i) => { result = true; throw new ApplicationException ("bleh"); return i + 3; };
240 Task<int> task = factory.FromAsync<int, int> (func.BeginInvoke, func.EndInvoke, 1, null);
241 var cont = task.ContinueWith (_ => continuationTest = true, TaskContinuationOptions.ExecuteSynchronously);
247 Assert.IsTrue (result);
248 Assert.IsTrue (continuationTest);
249 Assert.IsNotNull (task.Exception);
250 var agg = task.Exception;
251 Assert.AreEqual (1, agg.InnerExceptions.Count);
252 Assert.IsInstanceOfType (typeof (ApplicationException), agg.InnerExceptions[0]);
253 Assert.AreEqual (TaskStatus.Faulted, task.Status);
258 } catch (AggregateException) {
263 public void FromAsync_ArgumentsCheck ()
265 var result = new CompletedAsyncResult ();
267 factory.FromAsync (null, l => { });
269 } catch (ArgumentNullException) {
273 factory.FromAsync (result, null);
275 } catch (ArgumentNullException) {
279 factory.FromAsync (result, l => { }, TaskCreationOptions.LongRunning);
281 } catch (ArgumentOutOfRangeException) {
285 factory.FromAsync (result, l => { }, TaskCreationOptions.PreferFairness);
287 } catch (ArgumentOutOfRangeException) {
291 factory.FromAsync (result, l => { }, TaskCreationOptions.None, null);
293 } catch (ArgumentNullException) {
297 factory.FromAsync (null, l => { }, null, TaskCreationOptions.None);
299 } catch (ArgumentNullException) {
303 factory.FromAsync ((a, b) => null, l => { }, null, TaskCreationOptions.LongRunning);
305 } catch (ArgumentOutOfRangeException) {
310 public void FromAsync_Completed ()
312 var completed = new CompletedAsyncResult ();
315 Action<IAsyncResult> end = l => {
316 Assert.IsFalse (Thread.CurrentThread.IsThreadPoolThread, "#2");
317 valid = l == completed;
319 Task task = factory.FromAsync (completed, end);
320 Assert.IsTrue (valid == true, "#1");
324 public void FromAsync_CompletedWithException ()
326 var completed = new CompletedAsyncResult ();
328 Action<IAsyncResult> end = l => {
329 throw new ApplicationException ();
331 Task task = factory.FromAsync (completed, end);
332 Assert.AreEqual (TaskStatus.Faulted, task.Status, "#1");
336 public void FromAsync_CompletedCanceled ()
338 var completed = new CompletedAsyncResult ();
340 Action<IAsyncResult> end = l => {
341 throw new OperationCanceledException ();
343 Task task = factory.FromAsync (completed, end);
344 Assert.AreEqual (TaskStatus.Canceled, task.Status, "#1");
345 Assert.IsNull (task.Exception, "#2");
349 public void FromAsync_SimpleAsyncResult ()
351 var result = new TestAsyncResult ();
354 var task = factory.FromAsync (result, l => {
358 Assert.IsTrue (task.Wait (1000), "#1");
359 Assert.IsTrue (called, "#2");
363 public void FromAsync_ResultException ()
365 var result = new TestAsyncResult ();
367 var task = factory.FromAsync (result, l => {
368 throw new ApplicationException ();
372 Assert.IsFalse (task.Wait (1000), "#1");
373 } catch (AggregateException) {
376 Assert.AreEqual (TaskStatus.Faulted, task.Status, "#2");
380 public void FromAsync_ReturnInt ()
382 var result = new TestAsyncResult ();
385 var task = factory.FromAsync<int> (result, l => {
390 Assert.IsTrue (task.Wait (1000), "#1");
391 Assert.IsTrue (called, "#2");
392 Assert.AreEqual (4, task.Result, "#3");
396 public void FromAsync_Scheduler_Explicit ()
398 var result = new TestAsyncResult ();
400 var scheduler = new TestScheduler ();
402 var task = factory.FromAsync (result, l => {
404 }, TaskCreationOptions.None, scheduler);
406 Assert.IsTrue (task.Wait (5000), "#1");
407 Assert.IsTrue (called, "#2");
408 Assert.IsTrue (scheduler.ExecutedInline, "#3");
412 public void FromAsync_Scheduler_Implicit ()
414 var result = new TestAsyncResult ();
416 var scheduler = new TestScheduler ();
418 factory = new TaskFactory (scheduler);
420 Task task = factory.FromAsync (result, l => {
421 Assert.IsTrue (Thread.CurrentThread.IsThreadPoolThread, "#6");
423 }, TaskCreationOptions.AttachedToParent);
425 Assert.AreEqual (TaskCreationOptions.AttachedToParent, task.CreationOptions, "#1");
426 Assert.IsNull (task.AsyncState, "#2");
427 Assert.IsTrue (task.Wait (5000), "#3");
428 Assert.IsTrue (called, "#4");
429 Assert.IsTrue (scheduler.ExecutedInline, "#5");
433 public void FromAsync_BeginCallback ()
436 bool called2 = false;
438 var task = factory.FromAsync (
443 if ((TaskCreationOptions) c != TaskCreationOptions.AttachedToParent)
446 Assert.IsFalse (Thread.CurrentThread.IsThreadPoolThread, "#12");
455 "h", TaskCreationOptions.AttachedToParent);
457 Assert.AreEqual (TaskCreationOptions.None, task.CreationOptions, "#1");
458 Assert.AreEqual (TaskCreationOptions.AttachedToParent, (TaskCreationOptions) task.AsyncState, "#2");
459 Assert.IsTrue (task.Wait (5000), "#3");
460 Assert.IsTrue (called, "#4");
461 Assert.IsTrue (called2, "#5");