请参阅此代码:
Imports System.Threading
Private trd As Thread
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
trd = New Thread(AddressOf ThreadTask)
trd.IsBackground = True
trd.Start()
End Sub
Sub ThreadTask()
Thread.Sleep(50)
Button4.PerformClick()
End Sub
Private Sub Button4_Click(sender As System.Object, e As System.EventArgs) Handles Button4.Click
Me.Close()
End Sub
我试图模拟来自不同线程的按钮点击,但会发生以下错误:"未处理的类型' System.InvalidOperationException'发生在System.Windows.Forms.dll",在Button4.PerformClick()行。
如何跨线程使用此功能?
答案 0 :(得分:3)
您需要在创建控件的同一线程上执行UI命令。我们可以与代表一起做到这一点。这可以通过lambda轻松完成。
将Button4.PerformClick()
替换为:
Me.Invoke(Sub() Button4.PerformClick())