【问题标题】:SerialPorts and multi threading - Cross Thread operation not validSerialPorts 和多线程 - 跨线程操作无效
【发布时间】:2015-10-15 07:31:19
【问题描述】:

这是我第一次使用串行端口,所以我才知道它们在不同的线程上运行,我对多线程一无所知,所以我不知道从哪里开始修复我的代码,网络搜索让我更加困惑调用之类的东西。

这是我通过 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

【问题讨论】:

    标签: vb.net multithreading winforms serial-port


    【解决方案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
    

    【讨论】:

    • 嗨,我正在使用 Visual Studio 2008,这似乎不起作用。
    • 谢谢,您介意解释两个答案之间的区别吗?我在 Visual Studio 2010 上尝试了第一个答案,它可以工作。第一个答案在我看来也简单多了。
    • 这两个都会导致控件在 UI 线程上被操作。第一个使用 lamda,这使得它更简单恕我直言。
    猜你喜欢
    • 1970-01-01
    • 2011-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多