【发布时间】:2014-10-28 09:37:38
【问题描述】:
我在多个线程上使用 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 也会被激活。
【问题讨论】:
标签: c# wpf multithreading dialog