/// <summary> /// 不使用任何参数初始化 UIMessageProcessor 的新实例。 /// </summary> public UIMessageProcessor() { _MessageLoopThread = new Thread(new ThreadStart(_ThreadStartMethod)); _MessageLoopThread.IsBackground = true; _AsyncMessages = new Queue <UIMessage>(); _SyncMessages = new Queue <UIMessage>(); _Sender = null; _StoppedCallbackMethod = null; _State = UIMessageProcessorState.Stopped; }
/// <summary> /// 所有正在处理的消息处理完成后,停止在此界面消息处理器上运行消息循环。 /// </summary> /// <param name="sender">调用此方法的控件。</param> /// <param name="callbackMethod">回调方法。</param> public void Stop(Control sender, UIMessageProcessorStoppedHandler callbackMethod) { if (sender is null || callbackMethod is null) { throw new ArgumentNullException(); } if (State != UIMessageProcessorState.Running) { throw new InvalidOperationException(); } // _Sender = sender; _StoppedCallbackMethod = callbackMethod; State = UIMessageProcessorState.Stopping; }
// // 消息循环线程执行的方法。 private void _ThreadStartMethod() { Stopwatch sw = new Stopwatch(); while (true) { if (State == UIMessageProcessorState.Stopping && _GetProcessingAsyncMessageCount() <= 0) { break; } // sw.Restart(); MessageLoop(); sw.Stop(); if (sw.ElapsedMilliseconds < 1) { int count = 0; _MessageQueueLock.EnterReadLock(); try { count = _AsyncMessages.Count + _SyncMessages.Count; } finally { _MessageQueueLock.ExitReadLock(); } if (count > 0) { Thread.Sleep(0); } else { Thread.Sleep(1); } } else { Thread.Sleep(0); } } // _MessageQueueLock.EnterReadLock(); try { _AsyncMessages.Clear(); _SyncMessages.Clear(); } finally { _MessageQueueLock.ExitReadLock(); } State = UIMessageProcessorState.Stopped; // if (!(_Sender is null) && !(_StoppedCallbackMethod is null)) { _Sender.Invoke(_StoppedCallbackMethod, _Sender, this); _Sender = null; _StoppedCallbackMethod = null; } }