我正在使用Visual Basic編寫一個程序,它將從串口讀取使用外部控制器(Arduino)發送的文本命令。然而,當我嘗試測試代碼中,我得到一個錯誤:通過SerialPort.Read()獲取跨線程操作無效無效
Cross-thread Operation Not Valid
下面是代碼的樣子:
Private Sub SerialPort1_DataReceived(sender As Object, e As SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
Dim Data As String = SerialPort1.ReadExisting()
If Data = "l" Then
LeftRadio.Checked = True
ElseIf Data = "r" Then
RightRadio.Checked = True
ElseIf Data = "c" Then
CenterRadio.Checked = True
End If
End Sub
Private Sub connect_Click(sender As Object, e As EventArgs) Handles connect.Click
If Not SerialPort1.IsOpen Then
SerialPort1.PortName = "COM3"
SerialPort1.Open()
End If
End Sub
可能重複的[跨線程操作無效](http://stackoverflow.com/questions/5037470/cross-thread-operation-not-valid) – abatishchev
DataReceived事件在工作線程上運行,您無法更新任何控制直接。使用關於此異常的*數百個以前的問題來查找解決方案。 –