albert
albert

Reputation: 1571

ShowDialog from another thread and get result

I want to display a dialog from a secondary thread (not GUI). Main form has a method for showing the second form

    public string ShowDialogSafe()
    {
        if(this.InvokeRequired)
            return (string)Invoke(new MethodInvoker(() => ShowDialogSafe()));
        else
        {
            var frm = new Form2();
            if(frm.ShowDialog() == DialogResult.OK)
                return frm.MyResult;
            return String.Empty;
        }
    }

Is safe to call this from a secondary thread?

string s = this.ShowDialogSafe();

Will the secondary thread be blocked till the user closes Form2?

EDIT Why it's unsafe? Doesn't Invoke() guaranties that Form2 and it's controls are created on the GUI thread?

Upvotes: 0

Views: 332

Answers (1)

Dirk Huber
Dirk Huber

Reputation: 912

Yes, this code should work. Invoke is a blocking operation, so you non-gui-thread is waiting until the invoked method has finished. But usually, you would only put your non-gui code into a background thread and would show the UI elements within the gui thread (e.g. in a progress event of an BackgroundWorker or when the task has finished...)

Upvotes: 1

Related Questions