如何在另一个UI线程上显示对话框

本文关键字:显示 对话框 线程 UI 另一个 | 更新日期: 2023-09-27 18:28:08

我在多个线程上使用Show.Dialog,但出现了问题。当从UI线程调用的对话框关闭时,即使仍有一些对话框从另一个线程调用,MainWindow也会被激活。为了避免这种情况,我想在另一个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从监视线程调用,MainWindow也会被激活。

如何在另一个UI线程上显示对话框

您应该只从UI线程打开对话框。您可以使用调度器调用UI线程:

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

您可以简单地编写自己的ShowDialog / Show方法,然后调用调度器。

我希望我理解你的问题是正确的。