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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19858557/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 15:44:42  来源:igfitidea点击:

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

vb.netmultithreadingtextlabel

提问by babboon

I am trying to set text to label Label_caller.Text = phone_numberand 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.?

我正在尝试将文本设置为标签Label_caller.Text = phone_number,但出现此错误:“System.InvalidOperationException:跨线程操作无效:控制 'Label_caller' 从创建它的线程以外的线程访问。” 我该如何克服这个问题?我如何使用关键字我。?

回答by Szymon

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.

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

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.

您需要使用以下方法来更新文本框。这将检查是否需要在主线程上调用,如果需要,在 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

回答by Shital

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