“Cross-thread operation not valid” exception on inner controls

前端 未结 7 1455
南方客
南方客 2020-12-19 05:36

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

7条回答
  •  有刺的猬
    2020-12-19 06:22

    '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.

提交回复
热议问题