1

I have a method which takes in a .NET control and calls invoke against it like so:

Form.Invoke(Target);

However, I've run into an issue numerous times calling this method where due to timing or whatever, the form handle on the form doesn't exist, causing a Invoke or BeginInvoke cannot be called on a control until the window handle has been created error. In frustration, I jokingly changed the code to:

MainForm.Invoke(Target);

where MainForm is the main window of the application (the form handle for the main form is created at startup and remains active for the entire life cycle of the application). I ran all the tests and manually tested the application and everything seems to work fine despite the fact that this is used everywhere.

So my question is, what exactly is the meaning of invoking against a specific control? Is there any downside to just always invoking against a control you know will be active? If not, why does .NET have you invoke against a control in the first place (instead of just creating a static GuiThread.InvokeOnGuiThread(Blah);)?

kerkeslager
  • 1,364
  • 4
  • 17
  • 34
  • Most "until the window handle has been created" errors can easily be fixed by moving all initialization except control creation from the form constructor to the `Form.Load` event. – Albin Sunnanbo Mar 10 '11 at 15:42

1 Answers1

0

This question on SO : Why is InvokeRequired preferred over WindowsFormsSynchronizationContext? will provide you with a possible answer and the discussion and answers possible problems you will run into.

As for GuiThread.InvokeOnGuiThread(Blah); explain how it will work with multiple threads having message pumps and managing window controls (WindowsFormsSynchronizationContext solve this by being created on the GUI thread and attaching to the currently executing thread).

Community
  • 1
  • 1
Julien Roncaglia
  • 17,397
  • 4
  • 57
  • 75