2014-10-28 3 views
0

여러 스레드에서 Show.Dialog를 사용하고 있지만 문제가 있습니다. UI 스레드에서 호출 된 대화 상자가 닫히면 다른 스레드에서 호출 된 대화 상자가있는 경우에도 MainWindow가 활성화됩니다. 이 문제를 피하기 위해 다른 스레드의 UI 스레드에 대화 상자를 표시하고 싶습니다. 어떻게 가능합니까? 또는이 문제를 피할 수있는 다른 방법이 있습니까? UI 스레드에서 호출 CustomMsgBox 자동 폐쇄 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 }); 
     } 
    } 
} 

, MainWindow를 여전히 모니터링 스레드에서 호출 일부 CustomMsgBoxes이있는 경우에도 동작한다.

답변

2

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 방법을 쓰기 simpliy하고 디스패처를 호출 할 수 있습니다.

귀하의 질문에 대한 올바른 이해를 바랍니다.

+0

처음 정보가 부족하여 죄송합니다. showMsg()와 showErrorMsg() 두 가지 메소드가 다른 클래스에 존재합니다. 에러 모니터링 메소드가 주기적으로 다른 스레드에서 실행되는 ErrorMonitor 클래스에서 MainWindow를 얻으려면 어떻게해야합니까? Application.Current.MainWindow.Dispatcher.BeginInvoke를 시도했을 때 "다른 스레드가 소유하고 있기 때문에 호출하는 스레드는이 개체에 액세스 할 수 없습니다"라는 메시지가있는 예외가 발생했습니다. – user4134476

+0

@ user4134476 내 게시물을 업데이트합니다. 'this'를 사용해보십시오. – BendEg

+0

답장을 보내 주셔서 감사합니다. 하지만 "Dispatcher '기호를 해결할 수 없습니다라는 오류 메시지가 나타납니다. – user4134476

관련 문제