+ 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);
+ }
+ }
+ }
+