SerialPorts 和多线程 - 跨线程操作无效
SerialPorts and multi threading - Cross Thread operation not valid
这是我第一次使用串行端口,所以我才知道它们在不同的线程上运行,我对多线程一无所知,所以我不知道从哪里开始修复我的代码,网络搜索让我很困惑更多类似 Invoke 的东西。
这是我通过 rs232 端口连接的条码扫描器的完整代码,我只是接收数据并将其贴在标签上。
将标签文本设置为接收到的数据时出现错误...
Cross-thread operation not valid: Control 'Label1' accessed from a thread other than the thread it was created on.
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
你在哪里
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
这是我第一次使用串行端口,所以我才知道它们在不同的线程上运行,我对多线程一无所知,所以我不知道从哪里开始修复我的代码,网络搜索让我很困惑更多类似 Invoke 的东西。
这是我通过 rs232 端口连接的条码扫描器的完整代码,我只是接收数据并将其贴在标签上。
将标签文本设置为接收到的数据时出现错误...
Cross-thread operation not valid: Control 'Label1' accessed from a thread other than the thread it was created on.
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
你在哪里
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