I\'ve been struggling with this for quite a while: I have a function designed to add control to a panel with cross-thread handling, the problem is that though the panel and
'panel' and 'ctrl' must be created on the same thread, ie. you cannot have panel.InvokeRequired return different value than ctrl.InvokeRequired. That is if both panel and ctrl have the handles created or belong to a container with the handle created. From MSDN:
If the control's handle does not yet exist, InvokeRequired searches up the control's parent chain until it finds a control or form that does have a window handle. If no appropriate handle can be found, the InvokeRequired method returns false.
As it is right now your code is open to race conditions because the panel.InvokeNeeded
can return false because the panel is not yet created, then ctrl.InvokeNeeded
will certainly return false because most likely ctrl is not yet added to any container and then by the time you reach panel.Controls.Add
the panel was created in the main thread, so the call will fail.