基本上,您不会触摸在辅助线程上执行的方法中的控件。仅 UI 线程上的触摸控件。你通常可以这样做:
myPictureBox.Image = myImage
你现在写一个这样的方法:
Private Sub SetPictureBoxImage(img As Image)
If myPictureBox.InvokeRequired Then
myPictureBox.BeginInvoke(New Action(Of Image)(AddressOf SetPictureBoxImage), img)
Else
myPictureBox.Image = img
End If
End Sub
然后在辅助线程上调用它而不是直接设置 Image 属性:
SetPictureBoxImage(myImage)
请注意,无论是在 UI 线程还是辅助线程上调用该方法都会成功,因此无论您是否知道自己在辅助线程上,都可以调用它。
Check this out 了解更多信息。
编辑
Private Sub UpdateUI(img As Image, visible As Boolean)
If Me.InvokeRequired Then
Me.BeginInvoke(New Action(Of Image, Boolean)(AddressOf UpdateUI), img, visible)
Else
myPictureBox.Image = img
myPanel.Visible = visible
End If
End Sub
请注意,我使用了表单的 InvokeRequired 和 Invoke 成员,而不是特定的控件。实际上,只要它们属于同一个 UI 线程,它们属于哪个表单或控件并不重要,但对我来说,如果只有一个或使用表单,则使用相同的控件进行更新似乎是合乎逻辑的。
另请注意,委托的签名会更改以匹配方法的签名,以便它们具有相同数量和类型的参数。