Exemplo n.º 1
1
        private static void Main(string[] args)
        {
            CancellationTokenSource cts = new CancellationTokenSource();
            Console.CancelKeyPress +=
                (sender, e) =>
                {
                    e.Cancel = true;
                    cts.Cancel();
                };

            // Since Console apps do not have a SyncronizationContext, we're leveraging the built-in support
            // in WPF to pump the messages via the Dispatcher.
            // See the following for additional details:
            //   http://blogs.msdn.com/b/pfxteam/archive/2012/01/21/10259307.aspx
            //   https://github.com/DotNetAnalyzers/StyleCopAnalyzers/pull/1362
            SynchronizationContext previousContext = SynchronizationContext.Current;
            try
            {
                var context = new DispatcherSynchronizationContext();
                SynchronizationContext.SetSynchronizationContext(context);

                DispatcherFrame dispatcherFrame = new DispatcherFrame();
                Task mainTask = MainAsync(args, cts.Token);
                mainTask.ContinueWith(task => dispatcherFrame.Continue = false);

                Dispatcher.PushFrame(dispatcherFrame);
                mainTask.GetAwaiter().GetResult();
            }
            finally
            {
                SynchronizationContext.SetSynchronizationContext(previousContext);
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Processes all UI messages currently in the message queue.
        /// </summary>
        public static void DoEvents()
        {

            // Create new nested message pump.
            DispatcherFrame nestedFrame = new DispatcherFrame();



            // Dispatch a callback to the current message queue, when getting called, 
            // this callback will end the nested message loop.
            // note that the priority of this callback should be lower than the that of UI event messages.
            DispatcherOperation exitOperation = Dispatcher.CurrentDispatcher.BeginInvoke(
                                                  DispatcherPriority.Background, exitFrameCallback, nestedFrame);



            // pump the nested message loop, the nested message loop will 
            // immediately process the messages left inside the message queue.
            Dispatcher.PushFrame(nestedFrame);



            // If the "exitFrame" callback doesn't get finished, Abort it.
            if (exitOperation.Status != DispatcherOperationStatus.Completed)
            {
                exitOperation.Abort();
            }

        }
Exemplo n.º 3
0
 public static void DoEvents()
 {
     DispatcherFrame frame = new DispatcherFrame();
     Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background,
         new DispatcherOperationCallback(ExitFrame), frame);
     Dispatcher.PushFrame(frame);
 }
        public void Subscription_push_can_be_dispatched_on_designated_thread_blocking_scenario()
        {
            var threadId = -2;
            var threadIdFromTest = -1;
            IBus bus = null;

            var resetEvent = new ManualResetEvent(false);

            var uiThread = new Thread(
                () =>
                    {
                        Helpers.CreateDispatchContext();
                        var frame = new DispatcherFrame();
                        threadId = Thread.CurrentThread.ManagedThreadId;
                        bus = BusSetup.StartWith<RichClientFrontend>().Construct();
                        bus.Subscribe<MessageB>(
                            msg =>
                                {
                                    threadIdFromTest = Thread.CurrentThread.ManagedThreadId;
                                    frame.Continue = false;
                                },
                            c => c.DispatchOnUiThread());
                        resetEvent.Set();
                        Dispatcher.PushFrame(frame);
                    });
            uiThread.Start();
            resetEvent.WaitOne();
            bus.Publish(new MessageB());
            uiThread.Join();
            threadIdFromTest.ShouldBeEqualTo(threadId);
        }
Exemplo n.º 5
0
        public static void ExecuteWithDispatcher(Action<Dispatcher, Action> testBodyDelegate,
            int timeoutMilliseconds = 20000, string timeoutMessage = "Test did not complete in the spefied timeout")
        {
            var uiThreadDispatcher = Dispatcher.CurrentDispatcher;
            //ThreadingHelpers.UISynchronizationContext = new DispatcherSynchronizationContext(uiThreadDispatcher);

            var frame = new DispatcherFrame();

            // Set-up timer that will call Fail if the test is not completed in specified timeout

            TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);

            if (Debugger.IsAttached)
            {
                timeout = TimeSpan.FromDays(1);
            }

            Observable.Timer(timeout)
                .Subscribe(
                    _ => { uiThreadDispatcher.BeginInvoke(new Action(() => { Assert.True(false, timeoutMessage); })); });

            // Shedule the test body with current dispatcher (UI thread)
            uiThreadDispatcher.BeginInvoke(
                new Action(() => { testBodyDelegate(uiThreadDispatcher, () => { frame.Continue = false; }); }));

            // Run the dispatcher loop that will execute the above logic
            Dispatcher.PushFrame(frame);
        }
Exemplo n.º 6
0
        private static void Main(string[] args)
        {
            CancellationTokenSource cts = new CancellationTokenSource();
            Console.CancelKeyPress +=
                (sender, e) =>
                {
                    e.Cancel = true;
                    cts.Cancel();
                };

            SynchronizationContext previousContext = SynchronizationContext.Current;
            try
            {
                var context = new DispatcherSynchronizationContext();
                SynchronizationContext.SetSynchronizationContext(context);

                DispatcherFrame dispatcherFrame = new DispatcherFrame();
                Task mainTask = MainAsync(args, cts.Token);
                mainTask.ContinueWith(task => dispatcherFrame.Continue = false);

                Dispatcher.PushFrame(dispatcherFrame);
                mainTask.GetAwaiter().GetResult();
            }
            finally
            {
                SynchronizationContext.SetSynchronizationContext(previousContext);
            }
        }
 public static void DispatchFrame(DispatcherPriority priority = DispatcherPriority.Background)
 {
     DispatcherFrame frame = new DispatcherFrame();
     Dispatcher.CurrentDispatcher.BeginInvoke(priority,
         new DispatcherOperationCallback((f)=>((DispatcherFrame)f).Continue = false), frame);
     Dispatcher.PushFrame(frame);
 }
Exemplo n.º 8
0
        public void CountUploadedFiles(int counter, bool result, string fileName)
        {
            #region Needed for counter
            var dispatcherFrame = new DispatcherFrame(true);
            Dispatcher.CurrentDispatcher.BeginInvoke
            (
            DispatcherPriority.Background,
            (SendOrPostCallback)delegate(object arg)
            {
                var f = arg as DispatcherFrame;
                if (f != null) f.Continue = false;
            },
            dispatcherFrame
            );
            Dispatcher.PushFrame(dispatcherFrame);
            #endregion
            if (result)
            {

                textBlockCounter.Text = counter.ToString(CultureInfo.InvariantCulture) + " / " + _theImages.Count;
                if (fileName != "")
                    labelCopyingStatus.Content = "Copying " + fileName;
                else
                    labelCopyingStatus.Content = "";
            }
            else
                textBlockCounter.Text = counter.ToString(CultureInfo.InvariantCulture);
        }
Exemplo n.º 9
0
		public override void Fail(string message, string detailMessage)
		{
			base.Fail(message, detailMessage); // let base class write the assert to the debug console
			string stackTrace = "";
			try {
				stackTrace = new StackTrace(true).ToString();
			} catch {}
			lock (ignoredStacks) {
				if (ignoredStacks.Contains(stackTrace))
					return;
			}
			if (!dialogIsOpen.Set())
				return;
			if (!SD.MainThread.InvokeRequired) {
				// Use a dispatcher frame that immediately exits after it is pushed
				// to detect whether dispatcher processing is suspended.
				DispatcherFrame frame = new DispatcherFrame();
				frame.Continue = false;
				try {
					Dispatcher.PushFrame(frame);
				} catch (InvalidOperationException) {
					// Dispatcher processing is suspended.
					// We currently can't show dialogs on the UI thread; so use a new thread instead.
					new Thread(() => ShowAssertionDialog(message, detailMessage, stackTrace, false)).Start();
					return;
				}
			}
			ShowAssertionDialog(message, detailMessage, stackTrace, true);
		}
Exemplo n.º 10
0
        /// <summary>現在メッセージ待ち行列の中にある全UIメッセージを処理する</summary>
        private void DoEvents()
        {
            // 新しくネスト化されたメッセージ ポンプを作成
            DispatcherFrame frame = new DispatcherFrame();

            // DispatcherFrame (= 実行ループ) を終了させるコールバック
            DispatcherOperationCallback exitFrameCallback = (f) =>
            {
                // ネスト化されたメッセージ ループを抜ける
                ((DispatcherFrame)f).Continue = false;
                return null;
            };

            // 非同期で実行する
            // 優先度を Background にしているので、このコールバックは
            // ほかに処理するメッセージがなくなったら実行される
            DispatcherOperation exitOperation = Dispatcher.CurrentDispatcher.BeginInvoke(
                DispatcherPriority.Background, exitFrameCallback, frame);

            // 実行ループを開始する
            Dispatcher.PushFrame(frame);

            // コールバックが終了していない場合は中断
            if (exitOperation.Status != DispatcherOperationStatus.Completed)
            {
                exitOperation.Abort();
            }
        }
Exemplo n.º 11
0
 public void Open(FrameworkElement container)
 {
     if (container != null)
     {
         _container = container;
         // 通过禁用来模拟模态的对话框
         _container.IsEnabled = false;
         // 保持总在最上
         this.Owner = GetOwnerWindow(container);
         if (this.Owner != null)
         {
             this.Owner.Closing += new System.ComponentModel.CancelEventHandler(Owner_Closing);
         }
         // 通过监听容器的Loaded和Unloaded来显示/隐藏窗口
         _container.Loaded += new RoutedEventHandler(Container_Loaded);
         _container.Unloaded += new RoutedEventHandler(Container_Unloaded);
     }
     this.Show();
     try
     {
         ComponentDispatcher.PushModal();
         _dispatcherFrame = new DispatcherFrame(true);
         Dispatcher.PushFrame(_dispatcherFrame);
     }
     finally
     {
         ComponentDispatcher.PopModal();
     }
 }
 public static void DoEvents(DispatcherPriority priority = DispatcherPriority.Background) {
     DispatcherFrame frame = new DispatcherFrame();
     DXSplashScreen.SplashContainer.SplashScreen.Dispatcher.BeginInvoke(
         priority,
         new DispatcherOperationCallback(ExitFrame),
         frame);
     Dispatcher.PushFrame(frame);
 }
Exemplo n.º 13
0
 public static void DoEvents(DispatcherPriority nPrio)
 {
     DispatcherFrame nestedFrame = new DispatcherFrame();
     DispatcherOperation exitOperation = Dispatcher.CurrentDispatcher.BeginInvoke(nPrio, exitFrameCallback, nestedFrame);
     Dispatcher.PushFrame(nestedFrame);
     if (exitOperation.Status != DispatcherOperationStatus.Completed)
         exitOperation.Abort();
 }
        /// <summary>
        /// Waits until all pending messages up to the specified priority are processed.
        /// </summary>
        /// <param name="dispatcher">The dispatcher to wait on.</param>
        /// <param name="priority">The priority up to which all messages should be processed.</param>
        public static void ProcessMessages([NotNull] this Dispatcher dispatcher, DispatcherPriority priority)
        {
            Contract.Requires(dispatcher != null);

            var frame = new DispatcherFrame();
            dispatcher.BeginInvoke(priority, () => frame.Continue = false);
            Dispatcher.PushFrame(frame);
        }
Exemplo n.º 15
0
 public static void WaitWithPumping(this Task task)
 {
     if (task == null) throw new ArgumentNullException("task");
     var nestedFrame = new DispatcherFrame();
     task.ContinueWith(_ => nestedFrame.Continue = false);
     Dispatcher.PushFrame(nestedFrame);
     task.Wait();
 }
 public static void ProcessUITasks()
 {
     DispatcherFrame frame = new DispatcherFrame();
     Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.ContextIdle, new DispatcherOperationCallback(delegate (object parameter) {
         frame.Continue = false;
         return null;
     }), null);
     Dispatcher.PushFrame(frame);
 }
Exemplo n.º 17
0
 public void DoEvents() {
     var disp = GetDispatcher();
     if (disp != null) {
         DispatcherFrame frame = new DispatcherFrame();
         disp.BeginInvoke(DispatcherPriority.Background,
                 new DispatcherOperationCallback(ExitFrame), frame);
         Dispatcher.PushFrame(frame);
     }
 }
Exemplo n.º 18
0
 public static void DoEvents(this Dispatcher dispatcher)
 {
     var frame = new DispatcherFrame();
     dispatcher.BeginInvoke(
         DispatcherPriority.Background,
         new DispatcherOperationCallback(ExitFrame),
         frame);
     Dispatcher.PushFrame(frame);
 }
 internal override void PumpTill(Task task)
 {
     if (!task.IsCompleted)
     {
         var frame = new DispatcherFrame();
         task.ContinueWith(_ => frame.Continue = false, TaskScheduler.Default);
         Dispatcher.PushFrame(frame);
     }
 }
Exemplo n.º 20
0
 public static void WaitWithPumping(Task task)
 {
     if (task == null) throw new ArgumentNullException("task");
     var nestedFrame = new DispatcherFrame();
     task.ContinueWith(_ => nestedFrame.Continue = false);
     Dispatcher.PushFrame(nestedFrame);
     //execute this loop until all other tasks are done. it won't block the ui thread
     task.Wait();
 }
Exemplo n.º 21
0
		public void TestDispatcherOrder ()
		{
			Dispatcher d = Dispatcher.CurrentDispatcher;

			DispatcherFrame frame = new DispatcherFrame ();
			bool fail = true;
			int next = 1;
			
			d.BeginInvoke (DispatcherPriority.Normal, (Action) delegate {
				if (next != 3)
					throw new Exception ("Expected state 3, got " + next.ToString ());

				next = 4;
				Console.WriteLine ("First");
			});
			d.BeginInvoke (DispatcherPriority.Normal, (Action) delegate {
				if (next != 4)
					throw new Exception ("Expected state 4, got " + next.ToString ());

				next = 5;
				Console.WriteLine ("Second");
			});
			d.BeginInvoke (DispatcherPriority.Send, (Action) delegate {
				if (next != 1)
					throw new Exception ("Expected state 1, got " + next.ToString ());
				next = 2;
				Console.WriteLine ("High Priority");
				d.BeginInvoke (DispatcherPriority.Send, (Action) delegate {
					if (next != 2)
						throw new Exception ("Expected state 2, got " + next.ToString ());

					next = 3;
					Console.WriteLine ("INSERTED");
				});
			});
			d.BeginInvoke (DispatcherPriority.SystemIdle, (Action) delegate {
				if (next != 6)
					throw new Exception ("Expected state 6, got " + next.ToString ());
				
				Console.WriteLine ("Idle");
				frame.Continue = false;
				fail = false;
			});
			
			d.BeginInvoke (DispatcherPriority.Normal, (Action) delegate {
				if (next != 5)
					throw new Exception ("Expected state 5, got " + next.ToString ());
				next = 6;
				Console.WriteLine ("Last normal");
			});
			
			Dispatcher.PushFrame (frame);

			if (fail)
				throw new Exception ("Expected all states to run");
		}
Exemplo n.º 22
0
 public void DoEvents()
 {
     DispatcherFrame frame = new DispatcherFrame();
     Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(delegate (object f)
     {
         ((DispatcherFrame)f).Continue = false;
         return null;
     }), frame);
     Dispatcher.PushFrame(frame);
 }
Exemplo n.º 23
0
 private void DoAsync(Action action)
 {
     var frame = new DispatcherFrame();
     new Thread((ThreadStart)(() =>
     {
         action();
         frame.Continue = false;
     })).Start();
     Dispatcher.PushFrame(frame);
 }
Exemplo n.º 24
0
 internal static void WaitForPriority(DispatcherPriority priority)
 {
     DispatcherFrame frame = new DispatcherFrame();
     DispatcherOperation dispatcherOperation = Dispatcher.CurrentDispatcher.BeginInvoke(priority, new DispatcherOperationCallback(ExitFrameOperation), frame);
     Dispatcher.PushFrame(frame);
     if (dispatcherOperation.Status != DispatcherOperationStatus.Completed)
     {
         dispatcherOperation.Abort();
     }
 }
 static void DoEvents()
 {
     DispatcherFrame frame = new DispatcherFrame(true);
     Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate(object arg)
     {
         DispatcherFrame fr = arg as DispatcherFrame;
         fr.Continue = false;
     }, frame);
     Dispatcher.PushFrame(frame);
 }
Exemplo n.º 26
0
 /// <summary>
 /// Run all outstanding events queued on the provided Dispatcher
 /// </summary>
 /// <param name="dispatcher"></param>
 public static void DoEvents(this Dispatcher dispatcher)
 {
     var frame = new DispatcherFrame();
     Action<DispatcherFrame> action = _ => { frame.Continue = false; };
     dispatcher.BeginInvoke(
         DispatcherPriority.SystemIdle,
         action,
         frame);
     Dispatcher.PushFrame(frame);
 }
Exemplo n.º 27
0
 public static void ProcessUiTasks()
 {
     var frame = new DispatcherFrame();
     Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(delegate
     {
         frame.Continue = false;
         return null;
     }), null);
     Dispatcher.PushFrame(frame);
 }
Exemplo n.º 28
0
        // adapted from http://blogs.planetsoftware.com.au/paul/archive/2010/12/05/waiting-for-a-task-donrsquot-block-the-main-ui-thread.aspx
        public static void WaitWithPumping(this Task task)
        {
            if (task == null)
                return;

            var nestedFrame = new DispatcherFrame();
            task.ContinueWith(_ => nestedFrame.Continue = false);
            Dispatcher.PushFrame(nestedFrame);
            task.Wait();
        }
Exemplo n.º 29
0
 /// <summary>
 /// GUI Wait for x seconds
 /// </summary>
 /// <param name="seconds"></param>
 public static void Wait(double seconds)
 {
     var frame = new DispatcherFrame();
     new Thread((ThreadStart)(() =>
     {
         Thread.Sleep(TimeSpan.FromSeconds(seconds));
         frame.Continue = false;
     })).Start();
     Dispatcher.PushFrame(frame);
 }
Exemplo n.º 30
0
        public static void DoEvents()
        {
            var frame = new DispatcherFrame();

            Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => {
                frame.Continue = false;
            }));

            Dispatcher.PushFrame(frame);
        }
Exemplo n.º 31
0
        public static void Wait(System.Windows.Threading.Dispatcher Dispatcher, int Milliseconds)
        {
            var Frame = new DispatcherFrame();

            ThreadPool.QueueUserWorkItem(State =>
            {
                Thread.Sleep(Milliseconds);
                Frame.Continue = false;
            });

            MessageBox.Show("Complete!");
            Dispatcher.PushFrame(Frame);
            MessageBox.Show("Complete 2!");
        }
Exemplo n.º 32
0
        /// <summary>
        /// Equivalent to DoEvents
        /// </summary>
        /// <seealso cref="http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher.pushframe.aspx"/>
        public static void DoEvents(this Dispatcher dispatcher)
        {
            if (dispatcher.IsDisabled())
            {
                return;
            }

            var frame = new DispatcherFrame();

            dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, new Action <DispatcherFrame>((p) =>
            {
                p.Continue = false;
            }), frame);

            Dispatcher.PushFrame(frame);
        }
Exemplo n.º 33
0
        private void DoEvents()
        {
            if (doing)
            {
                return;
            }
            doing = true;
            var frame    = new System.Windows.Threading.DispatcherFrame();
            var callback = new System.Windows.Threading.DispatcherOperationCallback(obj =>
            {
                ((System.Windows.Threading.DispatcherFrame)obj).Continue = false;
                return(null);
            });

            System.Windows.Threading.Dispatcher.CurrentDispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Background, callback, frame);
            System.Windows.Threading.Dispatcher.PushFrame(frame);
            doing = false;
        }
        public static void ExitAllFrames()
        {
            Dispatcher dis = CurrentDispatcher;

            for (DispatcherFrame frame = dis.current_frame; frame != null; frame = frame.ParentFrame)
            {
                if (frame.exit_on_request)
                {
                    frame.Continue = false;
                }
                else
                {
                    //
                    // Stop unwinding the frames at the first frame that is
                    // long running
                    break;
                }
            }
        }
        void RunFrame(DispatcherFrame frame)
        {
            do
            {
                while (queue_bits != 0)
                {
                    for (int i = TOP_PRIO; i > 0 && queue_bits != 0; i--)
                    {
                        int current_bit = queue_bits & (1 << i);
                        if (current_bit != 0)
                        {
                            PokableQueue q = priority_queues [i];

                            do
                            {
                                DispatcherOperation task;

                                lock (q)
                                {
                                    task = (DispatcherOperation)q.Dequeue();
                                }

                                task.Invoke();

                                //
                                // call hooks.
                                //
                                if (task.Status == DispatcherOperationStatus.Aborted)
                                {
                                    hooks.EmitOperationAborted(task);
                                }
                                else
                                {
                                    hooks.EmitOperationCompleted(task);
                                }

                                if (!frame.Continue)
                                {
                                    return;
                                }

                                if (HasShutdownStarted)
                                {
                                    PerformShutdown();
                                    return;
                                }

                                // if we are done with this queue, leave.
                                lock (q)
                                {
                                    if (q.Count == 0)
                                    {
                                        queue_bits &= ~(1 << i);
                                        break;
                                    }
                                }

                                //
                                // If a higher-priority task comes in, go do that
                                //
                                if (current_bit < (queue_bits & ~current_bit))
                                {
                                    break;
                                }
                            }while (true);
                        }
                    }
                }
                hooks.EmitInactive();

                wait.WaitOne();
                wait.Reset();
            }while (frame.Continue);
        }