开发者

Cross-thread operation not valid in Label Array

I have a problem: When try to change th开发者_StackOverflow中文版e 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?


The Cliente_Receive event is occurring on a background thread. You need to use Control.Invoke to marshal the call back to the UI thread.

The only change you need to do is to change this:

'After this i Get just a number, for example 1 or 2
lblCSCH(canal).Text = canal

To:

'After this i Get just a number, for example 1 or 2
lblCHCH(canal).Invoke(Sub() lblCSCH(canal).Text = canal)


Try this in the form load section of your code.

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜