Alex Rivera | Logout

What's wrong with my cross-thread call in Windows Forms?

Asked 2010-06-15T14:43:52.480
10

I encounter a problem with a Windows Forms application.

A form must be displayed from another thread. So in the form class, I have the following code:

private delegate void DisplayDialogCallback();

public void DisplayDialog()
{
    if (this.InvokeRequired)
    {
        this.Invoke(new DisplayDialogCallback(DisplayDialog));
    }
    else
    {
        this.ShowDialog();
    }
}

Now, every time I run this, an InvalidOperationException is thrown on the line this.ShowDialog();:

"Cross-thread operation not valid: Control 'SampleForm' accessed from a thread other than the thread it was created on."

What's wrong with this piece of code? Isn't it a valid way to make cross-thread calls? Is there something special with ShowDialog()?

Edit
Report

2 Answers

8

You're probably executing this code before the form has been shown.
Therefore, InvokeRequired is returning false.

answered 2010-06-15T14:49:38.153
2

You are likely getting to this code before the form has been shown and therefore the window handle has not been created.

You can add this code before your code and all should be good:

if (! this.IsHandleCreated)
   this.CreateHandle();

Edit: There's another problem with your code. Once the form is displayed, you cannot call ShowDialog() again. You will get an invalid operation exception. You may want to modify this method as others have proposed.

You might be better served calling the ShowDialog() directly from the calling class and have another method for BringToFront() or something like that...

answered 2010-06-15T15:14:22.343

Your Answer