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

Posted by MainMa on Stack Overflow See other posts from Stack Overflow or by MainMa
Published on 2010-06-15T14:43:52Z Indexed on 2010/06/15 16:22 UTC
Read the original article Hit count: 362

Hi,

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()?

© Stack Overflow or respective owner

Related posts about c#

Related posts about winforms