2

我正在尝试从单独的线程访问动态生成的控件。但是我的代码总是出现“堆​​栈溢出异常”。

我正在使用以下代码:

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。但我不明白为什么。也许有人可以告诉我我做错了什么。

4

1 回答 1

3

您没有在标签的线程上调用方法 SetLabelTextCallback,
因此您将在同一个线程上再次调用,并且 InvokeRequired 永远不会为假

Delegate Sub SetLabelTextCallback(ByVal LabelName As String, ByVal text As String) 

Private Sub SetLabelText(ByVal LabelName As String, ByVal text As String) 
    Dim l as Label = CType(Me.Controls(LabelName), Label)
    if l.InvokeRequired then
        Dim d As New SetLabelTextCallback(AddressOf SetLabelText) 
        l.Invoke(d, new Object() {LabelName, text} ) 
    Else 
        l.Text = text 
    End If 
End Sub 
于 2012-06-02T20:17:50.763 回答