c# - 如何显示另一个UI线程上的对话框

标签 c# wpf multithreading dialog

我在多个线程上使用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-Thread:

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

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

希望我理解您的问题正确。

关于c# - 如何显示另一个UI线程上的对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26604980/

相关文章:

java - 创建过多的线程

c# - 图像 Url 出现问题,自动将文件夹名称添加到为图像创建的 URL

wpf - 列表框数据模板文本溢出

c# - 离线时 App Insights 遥测不发送

Python 2.7 - Linux - 无限循环,放弃 CPU 给其他线程/进程

c++ - 多线程设计,C++保护全局成员

C# 将文件保存到内存并获取在以文件路径作为输入的方法中使用的路径

c# - 更改 gethostentry 返回的 IP 的最后八位字节

c# - 无法分配新套接字,抛出无效参数异常

c# - 如何在网格中移动项目