跨线程操作在标签数组中无效
我有一个问题:当尝试更改标签数组的文本 (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
我该如何解决这个问题?
I have a problem: When try to change the text of a label array (label(1).text = "Lol") then I get a error:
"Cross-thread operation not valid: Control 'lblCSCH1' accessed from a thread other than the thread it was created on."
The code is this:
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
How can I resolve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Cliente_Receive
事件发生在后台线程上。您需要使用Control.Invoke
将回调编组回 UI 线程。您需要做的唯一更改是将其更改
为:
The
Cliente_Receive
event is occurring on a background thread. You need to useControl.Invoke
to marshal the call back to the UI thread.The only change you need to do is to change this:
To:
在代码的表单加载部分尝试此操作。
Try this in the form load section of your code.