2013-04-30 51 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