WPF 中实现 Winfrom 中 Application.DoEvents() 方法

熟悉 Winfrom 中 Application.DoEvents() 方法的朋友一定用过此方法,此方法可以立即处理当前在消息队列中的所有 Windows 消息。 如在一个按钮单击事件中,需要每一秒改变label的Text属性,如下代码:

  1.      private void button1_Click(object sender, EventArgs e) 
  2.      { 
  3.          for (int i = 0; i < 50; i++) 
  4.              Thread.Sleep(500); 
  5.              this.label1.Text = i.ToString(); 
  6.      } 

编译运行,单击按钮,你并不会见到lable一直改变,等到执行完,你只会看见49。而加上 Application.DoEvents() 方法则可以看到一直更改的文本

  1. private void button1_Click(object sender, EventArgs e) 
  2.     for (int i = 0; i < 50; i++) 
  3.  
  4.         Thread.Sleep(500); 
  5.         this.label1.Text = i.ToString(); 
  6.         Application.DoEvents(); 
  7.  

好了,废话不多说了,不明白的可以参考 Application.DoEvents 方法

      在 WPF 中没有 Application.DoEvents() 方法,看下面实现代码:

  1. public static class DispatcherHelper 
  2.     [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)] 
  3.     public static void DoEvents() 
  4.     { 
  5.         DispatcherFrame frame = new DispatcherFrame(); 
  6.         Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(ExitFrames), frame); 
  7.         try { Dispatcher.PushFrame(frame); } 
  8.         catch (InvalidOperationException) { } 
  9.     } 
  10.     private static object ExitFrames(object frame) 
  11.     { 
  12.         ((DispatcherFrame)frame).Continue = false
  13.         return null
  14.     } 

调用:

  1. DispatcherHelper.DoEvents(); 
原文地址:https://www.cnblogs.com/andyzhao365/p/2225479.html