SerialPorts和多线程 - 交叉线程操作无效

时间:2015-10-15 07:31:20

标签: vb.net multithreading winforms serial-port

这是我第一次使用串口,​​所以我才知道它们在不同的线程上运行,我对多线程没有任何线索所以我不知道从哪里开始修复我的代码,网页搜索让我更加困惑像Invoke这样的东西。

这是我通过rs232端口连接的条码扫描器的完整代码,我只是接收数据并将其放在标签上。

将标签文本设置为接收数据时,我收到错误...

  

跨线程操作无效:控制从其创建的线程以外的线程访问的“Label1”。

Imports System.IO.Ports

Public Class Form1

Dim WithEvents com4 As New SerialPort

Private Sub com4_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles com4.DataReceived
    Dim returnStr As String
    returnStr = com4.ReadExisting
    Label1.Text = returnStr
    com4.DiscardInBuffer()
End Sub


Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Try
        With com4
            .PortName = "Com4"
            .BaudRate = 38400 '9600
            .Parity = Parity.None
            .DataBits = 8
            .StopBits = StopBits.One
        End With
        com4.Open()

    Catch ex As Exception
        MsgBox(ex.ToString)
    End Try
End Sub

End Class

1 个答案:

答案 0 :(得分:1)

你在哪里

    Label1.Text = returnStr

替换该行
    Me.BeginInvoke(Sub()
                       Label1.Text = returnStr
                   End Sub)

编辑:

你在哪里

    Label1.Text = returnStr

替换该行
    UpdateLabel(returnStr)

并添加此代码

Private Delegate Sub UpdateLabelDelegate(theText As String)
Private Sub UpdateLabel(theText As String)
    If Me.InvokeRequired Then
        Me.Invoke(New UpdateLabelDelegate(AddressOf UpdateLabel), theText)
    Else
        Label1.text = theText
    End If
End Sub