Merge pull request #5714 from alexischr/update_bockbuild
[mono.git] / mcs / tests / test-async-55.cs
1 using System;
2 using System.Threading;
3 using System.Threading.Tasks;
4
5 class MyContext : SynchronizationContext
6 {
7         public override void Post (SendOrPostCallback d, object state)
8         {
9                 base.Post (d, state);
10         }
11
12         public override void Send (SendOrPostCallback d, object state)
13         {
14                 base.Send (d, state);
15         }
16 }
17
18 class X
19 {
20         static TaskCompletionSource<bool> tcs;
21         static ManualResetEvent mre, mre2;
22         static int main_thread_id;
23
24         public static int Main ()
25         {
26                 main_thread_id = Thread.CurrentThread.ManagedThreadId;
27                 Console.WriteLine ("{0}:Main start", main_thread_id);
28
29                 mre = new ManualResetEvent (false);
30                 mre2 = new ManualResetEvent (false);
31                 tcs = new TaskCompletionSource<bool> ();
32
33                 Task.Factory.StartNew (new Func<Task> (ExecuteAsync), new CancellationToken (), TaskCreationOptions.LongRunning, TaskScheduler.Default);
34
35                 if (!mre.WaitOne (1000))
36                         return 1;
37
38                 // Have to wait little bit longer for await not to take quick path
39                 Thread.Sleep (10);
40
41                 Console.WriteLine ("{0}:Main Set Result", Thread.CurrentThread.ManagedThreadId);
42
43                 SynchronizationContext.SetSynchronizationContext (new MyContext ());
44
45                 tcs.SetResult (true);
46
47                 if (!mre2.WaitOne (1000))
48                         return 2;
49
50                 Console.WriteLine ("ok");
51                 return 0;
52         }
53
54         static async Task ExecuteAsync ()
55         {
56                 var t = Thread.CurrentThread;
57                 Console.WriteLine ("{0} - started ", t.ManagedThreadId);
58
59                 mre.Set ();
60
61                 await tcs.Task;
62                 t = Thread.CurrentThread;
63                 Console.WriteLine ("{0} - resumed ", t.ManagedThreadId);
64
65                 //
66                 // Continuation cannot resume on main thread because it has synchronization context set
67                 //
68                 if (main_thread_id != Thread.CurrentThread.ManagedThreadId)
69                         mre2.Set ();
70         }
71 }