vb.net accessed from a thread other than the thread it was created on

孤街醉人 提交于 2019-12-07 03:01:14

问题


I am trying to set text to label Label_caller.Text = phone_number and I get this error: "System.InvalidOperationException: Cross-thread operation not valid: Control 'Label_caller' accessed from a thread other than the thread it was created on." How do I overcome this problem? How do I use keyword Me.?


回答1:


In Windows, you can access UI elements only on the UI thread. For that reason, if you need to access them from another thread, you may need to invoke that action on the UI thread.

You need to use the following method to update the text box. This will check if invoking on the main thread is required and if needed, call the same method on the UI thread.

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



回答2:


I am probably answering quite late but adding following code in form load event seems solving problem.

Not sure though it's perfect answer or not:

System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = False


来源:https://stackoverflow.com/questions/19858557/vb-net-accessed-from-a-thread-other-than-the-thread-it-was-created-on

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!