我有一个问题:当尝试更改标签数组的文本(label(1).text =“Lol”)时,我收到错误:
"Cross-thread operation not valid: Control 'lblCSCH1' accessed from a thread other than the thread it was created on."
代码是这样的:
Private Sub Cliente_Receive(ByRef message As String) Handles Cliente.Receive
Dim anterior As String
Dim corte As Integer
Dim canal As String
Dim lblCSCH() As Label = {lblCSCH0, lblCSCH1, lblCSCH2, lblCSCH3, lblCSCH4, lblCSCH5, lblCSCH6, lblCSCH7, lblCSCH8, lblCSCH9, lblCSCH10}
If Microsoft.VisualBasic.Left(message, 3) = "<ch" Then
corte = InStr(message, ">")
If corte > 0 Then
corte = corte - 1
canal = Replace(LTrim(Replace(Replace(Replace(Replace(Microsoft.VisualBasic.Left(message, corte), "h", ""), "c", ""), "<", ""), "0", " ")), " ", "0")
'After this i Get just a number, for example 1 or 2
lblCSCH(canal).Text = canal
End If
End If
End Sub
我该如何解决这个问题?
答案 0 :(得分:1)
在代码的表单加载部分中尝试此操作。
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Control.CheckForIllegalCrossThreadCalls = False
'Rest of load form data
End Sub
答案 1 :(得分:1)
Cliente_Receive
事件发生在后台线程上。您需要使用Control.Invoke
将回调编组回UI线程。
您需要做的唯一更改是更改此内容:
'After this i Get just a number, for example 1 or 2
lblCSCH(canal).Text = canal
要:
'After this i Get just a number, for example 1 or 2
lblCHCH(canal).Invoke(Sub() lblCSCH(canal).Text = canal)