user4134476
user4134476

Reputation: 385

How can I show dialog on UI thread from another

I'm using Show.Dialog on multiple threads, but there is a problem. When the dialog box called from the UI thread is closed, the MainWindow is activated even when there still are some dialog boxes called from another thread. In order to avoid this, I'd like to show dialog boxes on the UI thread from another, but how is it possible? Or is there any other way for me to avoid this problem?

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 });
        }
    }
}

When the CustomMsgBox called from the UI thread is automatically closed, the MainWindow is activated even when there still are some CustomMsgBoxes called from the monitoring thread.

Upvotes: 1

Views: 4838

Answers (1)

BendEg
BendEg

Reputation: 21088

You should only open the Dialog from the UI thread. You can invoke the UI-Thread with the dispatcher:

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

You can simpliy write your own ShowDialog / Show method, and then call the dispatcher.

I hope i understood your question correct.

Upvotes: 4

Related Questions