2013-04-30 46 views
0

我已经创造了新的WPF项目,在主窗口中我做:Dispatcher.Invoke挂起主窗口

public MainWindow() 
{ 
    InitializeComponent(); 

    Thread Worker = new Thread(delegate(){ 

     this.Dispatcher.BeginInvoke(DispatcherPriority.SystemIdle, new Action(delegate 
     { 
      while (true) 
      { 
       System.Windows.MessageBox.Show("asd"); 

       Thread.Sleep(5000); 
      } 
     })); 
    }); 

    Worker.Start(); 
} 

问题之间的那些邮件主窗口挂起。我如何使它异步工作?

回答

4

因为您要让UI线程进入睡眠状态,并且您不让调度程序返回到处理其主消息循环。

尝试更多的东西一样

Thread CurrentLogWorker = new Thread(delegate(){ 
    while (true) { 
     this.Dispatcher.Invoke(
       DispatcherPriority.SystemIdle, 
       new Action(()=>System.Windows.MessageBox.Show("asd"))); 
     Thread.Sleep(5000); 
    } 
});  
+0

线程还应该将IsBackground设置为true,以便它将与应用程序 – 2013-04-30 11:24:24

+0

一起退出非常感谢。 – Taras 2013-04-30 11:26:40

0

你怎么试图存档?

您的while循环和Thread.Sleep()在UI线程上执行,所以难怪MainWindow挂起。

您应该将这两个外部的BeginInvoke调用和ActionBox中只有MessageBox.Show放在一起。

0

您发送给Dispather.BeginInvoke的委托代码在主线程中执行。
您不应该在BeginInvoke方法的委托中进行睡眠或做其他长时间工作。

你应该在这样的BeginInovke方法之前做很长时间的工作。

Thread CurrentLogWorker = new Thread(delegate(){ 
    while (true) 
    { 
     this.Dispatcher.Invoke(DispatcherPriority.SystemIdle, new Action(delegate 
     { 
      System.Windows.MessageBox.Show("asd"); 
     })); 

     Thread.Sleep(5000); 
    } 
}); 
CurrentLogWorker.Start(); 
+0

你不想在那里有'BeginInvoke',否则线程不会等待消息框进入睡眠状态。 – 2013-04-30 11:25:27

+0

是的,你是对的 – 2013-04-30 11:59:44