我正在尝试从单独的线程访问动态生成的控件。但是我的代码总是出现“堆栈溢出异常”。
我正在使用以下代码:
Private _workerThread As Threading.Thread
Private Sub Main_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Dim Label As New Label
Label.Name = "Label1"
Label.Location = New System.Drawing.Point(12, 12)
Label.Text = String.Empty
Label.AutoSize = True
Controls.Add(Label)
_workerThread = New Threading.Thread(AddressOf DoWork)
_workerThread.Priority = Threading.ThreadPriority.BelowNormal
_workerThread.Start()
End Sub
Private Sub DoWork()
SetLabelText("Label1", "text")
End Sub
Delegate Sub SetLabelTextCallback(ByVal LabelName As String, ByVal text As String)
Private Sub SetLabelText(ByVal LabelName As String, ByVal text As String)
If CType(Me.Controls(LabelName), Label).InvokeRequired Then
Dim d As New SetLabelTextCallback(AddressOf SetLabelText)
d.Invoke(LabelName, text)
Else
CType(Me.Controls(LabelName), Label).Text = text
End If
End Sub
显然 InvokeRequired 永远不会变为 False。但我不明白为什么。也许有人可以告诉我我做错了什么。