线程安全调用窗体控件数组

时间:2012-06-02 19:46:04

标签: vb.net thread-safety controls stack-overflow

我试图从单独的线程访问动态生成的Control。 但是我的代码总是得到“Stack Overflow Exception”。

我正在使用以下代码:

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

1 个答案:

答案 0 :(得分:3)

您没有在Label的线程上调用方法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