2014-10-28 62 views
0

我在多線程上使用Show.Dialog,但出現了問題。 當從UI線程調用的對話框關閉時,即使仍然有一些從另一個線程調用的對話框,MainWindow也會被激活。 爲了避免這種情況,我想在另一個UI線程上顯示對話框,但這怎麼可能? 或者有沒有其他方法可以避免這個問題?我怎樣才能在另一個UI線程上顯示對話框

public partial class CustomMsgBox : Window 
{ 
    //this class implements a method that automatically 
    //closes the window of CustomMsgBox after the designated time collapsed 

    public CustomMsgBox(string message) 
    { 
     InitializeComponent(); 
     Owner = Application.Current.MainWindow; 
     //several necessary operations... 
    } 

    public static void Show(string message) 
    { 
     var customMsgBox = new CustomMsgBox(message); 
     customMsgBox.ShowDialog(); 
    } 
} 

public class MessageDisplay 
{ 
    //on UI thread 
    public delegate void MsgEventHandler(string message); 
    private event MsgEventHandler MsgEvent = message => CustomMsgBox.Show(message); 

    private void showMsg() 
    { 
     string message = "some message" 
     Dispatcher.Invoke(MsgEvent, new object[] { message }); 
    } 
} 

public class ErrorMonitor 
{ 
    //on another thread (monitoring errors) 
    public delegate void ErrorEventHandler(string error); 
    private event ErrorEventHandler ErrorEvent = error => CustomMsgBox.Show(error); 
    private List<string> _errorsList = new List<string>(); 

    private void showErrorMsg() 
    { 
     foreach (var error in _errorsList) 
     { 
      Application.Current.Dispatcher.BeginInvoke(ErrorEvent, new object[] { error }); 
     } 
    } 
} 

當從UI線程調用的CustomMsgBox自動關閉, 的主窗口被激活,即使還有一些CustomMsgBoxes從監視線程調用。

回答

2

您應該只從UI線程打開對話框。您可以與調度程序調用UI線程:

// call this instead of showing the dialog direct int the thread 
this.Dispatcher.Invoke((Action)delegate() 
{ 
    // Here you can show your dialiog 
}); 

您可以simpliy寫自己的ShowDialog/Show方法,然後調用調度。

我希望我明白你的問題是正確的。

+0

我很抱歉缺少我第一次提供的信息,但2種方法showMsg()和showErrorMsg()存在於不同的類中。如何在ErrorMonitor類中獲取我的MainWindow,其中錯誤監視方法是在其他線程中定期執行的。當我嘗試Application.Current.MainWindow.Dispatcher.BeginInvoke時,發生了一個異常消息「由於不同的線程擁有它,調用線程無法訪問此對象」。 – user4134476 2014-10-28 11:52:26

+0

@ user4134476我更新了我的帖子。嘗試使用'this'。 – BendEg 2014-10-29 08:24:17

+0

謝謝你的回覆。但是,我收到了錯誤消息「無法解析符號」調度程序「」。 – user4134476 2014-10-29 09:07:09

相關問題