从其创建的线程以外的线程访问的vb.net

bab*_*oon 6 vb.net multithreading text label

我试图将文本设置为标签Label_caller.Text = phone_number,我收到此错误:"System.InvalidOperationException:跨线程操作无效:控件'Label_caller'从其创建的线程以外的线程访问." 我该如何克服这个问题?我如何使用关键字Me?

Szy*_*mon 17

在Windows中,您只能在UI线程上访问UI元素.因此,如果需要从另一个线程访问它们,则可能需要在UI线程上调用该操作.

您需要使用以下方法来更新文本框.这将检查是否需要在主线程上调用,如果需要,在UI线程上调用相同的方法.

Private Sub UpdateTextBox(ByVal phone_number As String)
    If Me.InvokeRequired Then
        Dim args() As String = {phone_number}
        Me.Invoke(New Action(Of String)(AddressOf UpdateTextBox), args)
        Return
    End IF
    Label_caller.Text = phone_number
End Sub
Run Code Online (Sandbox Code Playgroud)