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種方法showMsg()和showErrorMsg()存在於不同的類中。如何在ErrorMonitor類中獲取我的MainWindow,其中錯誤監視方法是在其他線程中定期執行的。當我嘗試Application.Current.MainWindow.Dispatcher.BeginInvoke時,發生了一個異常消息「由於不同的線程擁有它,調用線程無法訪問此對象」。 – user4134476 2014-10-28 11:52:26
@ user4134476我更新了我的帖子。嘗試使用'this'。 – BendEg 2014-10-29 08:24:17
謝謝你的回覆。但是,我收到了錯誤消息「無法解析符號」調度程序「」。 – user4134476 2014-10-29 09:07:09