Form.InvokeRequired returns false until the form is displayed.
I did a simple test:
Form2 f2 = new Form2(); Thread t = new Thread(new ThreadStart(() => PrintInvokeRequired(f2))); t.Start(); t.Join(); f2.Show(); t = new Thread(new ThreadStart(() => PrintInvokeRequired(f2))); t.Start(); t.Join();
with assistant
private void PrintInvokeRequired(Form form) { Console.WriteLine("IsHandleCreated: " + form.IsHandleCreated + ", InvokeRequired: " + form.InvokeRequired); }
output
IsHandleCreated: False, InvokeRequired: False
IsHandleCreated: True, InvokeRequired: True
Also note that this is somewhat described on MSDN :
If a control handle is not already installed, InvokeRequired searches to control the parent chain until it finds a control or form that has a window handle. If not, you can find the handle. InvokeRequired returns false.
This means that InvokeRequired can return false if Invoke is not required (the call is in the same thread), or if the control was created on another thread, but the control handle has not yet been created.
In the case where the control handle has not yet been created, you should not just call properties, methods, or events on the control. This can cause the control knob created against the background of the flow, isolating the flow control without a message pump and the application is unstable.
You can protect against this case also by checking the value of IsHandleCreated when InvokeRequired returns false in the background thread. If the control handle has not yet been created, you must wait until it was created before invoking Invoke or BeginInvoke. Typically, this only happens if a background thread is created in the primary form constructor for the application (as in Application.Run (new MainForm ()), before the form has been shown or Application.Run is called.
Your solution should also check IsHandleCreated .
Edit:
Handle can be created at any time inside the WebBrowser control or externally. This does not automatically create a handle to the parent form.
I created an example:
public Form2() { InitializeComponent(); Button button1 = new Button(); this.Controls.Add(button1); Console.WriteLine("button1: " + button1.IsHandleCreated + " this: " + this.IsHandleCreated); var tmp = button1.Handle;
with output:
button1: False this: False
button1: True this: False