2014-10-28 26 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

相关问题