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