【问题标题】:Handling Exception in Visual Studio在 Visual Studio 中处理异常
【发布时间】:2014-02-05 09:46:03
【问题描述】:

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

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

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

但程序仍然冻结!

【问题讨论】:

  • 那些是第一次机会例外,应该被忽略。它们不会导致您的程序冻结。
  • 如果没有什么可看的……
  • 接收第一次机会异常通知 (msdn.microsoft.com/en-us/library/dd997368%28v=vs.110%29.aspx) 但正如 John 所说,它们不会导致您的程序冻结,似乎您的 SerialPort 未正确初始化。

标签: vb.net exception-handling first-chance-exception


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

它应该停止阅读,但我已经遇到过这样的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 2010-09-12
    • 1970-01-01
    • 2018-04-01
    • 2017-01-27
    相关资源
    最近更新 更多