-1

我无法处理这些导致我的程序冻结的错误。

如何处理所有这些?这是我的调试器输出:

A first chance exception of type 'System.IO.IOException' occurred in System.dll
A first chance exception of type 'System.InvalidOperationException' occurred in System.dll
A first chance exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll
A first chance exception of type 'System.TimeoutException' occurred in System.dll
A first chance exception of type 'System.IO.IOException' occurred in System.dll

我用了

Try
    Dim str As String = SerialPort.ReadLine()
Catch ex As Exception
    MsgBox(ex)
End Try

但是程序仍然冻结!

4

1 回答 1

1

ReadLine 方法会阻塞程序,直到它完成读取。

您应该使用 DataReceived 事件,如下所示:

Public WithEvents serial As New SerialPort("COM1")
Public Sub serial_OnDataReceived(ByVal sender As Object, ByVal e As SerialDataReceivedEventArgs) Handles serial.DataReceived
    MsgBox(e.ToString)
End Sub

当然 Open() 你的 SerialPort ;)

编辑 :

如果您真的想使用 ReadLine(),请尝试设置超时:

Try
    SerialPort.ReadTimeout = 1000
    Dim str As String = SerialPort.ReadLine()
Catch ex As Exception
    MsgBox(ex)
End Try

它应该停止阅读,但我已经以这种方式遇到了问题。

于 2014-02-05T10:22:27.880 回答