2 using System
.Threading
;
3 using System
.Threading
.Tasks
;
5 class MyContext
: SynchronizationContext
7 public override void Post (SendOrPostCallback d
, object state
)
12 public override void Send (SendOrPostCallback d
, object state
)
20 static TaskCompletionSource
<bool> tcs
;
21 static ManualResetEvent mre
, mre2
;
22 static int main_thread_id
;
24 public static int Main ()
26 main_thread_id
= Thread
.CurrentThread
.ManagedThreadId
;
27 Console
.WriteLine ("{0}:Main start", main_thread_id
);
29 mre
= new ManualResetEvent (false);
30 mre2
= new ManualResetEvent (false);
31 tcs
= new TaskCompletionSource
<bool> ();
33 Task
.Factory
.StartNew (new Func
<Task
> (ExecuteAsync
), new CancellationToken (), TaskCreationOptions
.LongRunning
, TaskScheduler
.Default
);
35 if (!mre
.WaitOne (1000))
38 // Have to wait little bit longer for await not to take quick path
41 Console
.WriteLine ("{0}:Main Set Result", Thread
.CurrentThread
.ManagedThreadId
);
43 SynchronizationContext
.SetSynchronizationContext (new MyContext ());
47 if (!mre2
.WaitOne (1000))
50 Console
.WriteLine ("ok");
54 static async Task
ExecuteAsync ()
56 var t
= Thread
.CurrentThread
;
57 Console
.WriteLine ("{0} - started ", t
.ManagedThreadId
);
62 t
= Thread
.CurrentThread
;
63 Console
.WriteLine ("{0} - resumed ", t
.ManagedThreadId
);
66 // Continuation cannot resume on main thread because it has synchronization context set
68 if (main_thread_id
!= Thread
.CurrentThread
.ManagedThreadId
)