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

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


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


Try this one:

private delegate void DisplayDialogCallback();public void DisplayDialog(){    if (this.InvokeRequired)    {        this.Invoke(new DisplayDialogCallback(DisplayDialog));    }    else    {        if (this.Handle != (IntPtr)0) // you can also use: this.IsHandleCreated        {            this.ShowDialog();            if (this.CanFocus)            {                this.Focus();            }        }        else        {            // Handle the error        }    }}

Please note that InvokeRequired returns

true if the control's Handle was created on a different thread than the calling thread (indicating that you must make calls to the control through an invoke method); otherwise, false.

and therefore, if the control has not been created, the return value will be false!


I believe what is happening here is that this code is being run before the Form is ever shown.

When a Form is created in .Net it does not immediately gain affinity for a particular thread. Only when certain operations are performed like showing it or grabbing the handle does it gain affinity. Before that happens it's hard for InvokeRequired to function correctly.

In this particular case no affinity is established and no parent control exists so InvokeRequired returns false since it can't determine the original thread.

The way to fix this is to establish affinity for your control when it's created on the UI thread. The best way to do this is just to ask the control for it's handle property.

var notUsed = control.Handle;