0

我试图通过这样的串行端口发送数据来捕获超时异常,

    ReadTimeout = 1000     '// 1000 milliseconds = 1 seconds
    WriteTimeout = 1000    '// 1000 milliseconds = 1 seconds

    Try
        If COMPort.IsOpen Then
            COMPort.Write(dataToSend)
        End If

    Catch ex As Exception
            COMPort.DiscardInBuffer()
            COMPort.DiscardOutBuffer()

            Dim t As New Thread(AddressOf ClosePort)
            Thread.Sleep(1000)
            t.Start()
    End Try

Private Sub ClosePort()
    If COMPort.IsOpen Then
        COMPort.DiscardInBuffer()
        COMPort.DiscardOutBuffer()

        Try
            COMPort.Close()

        Catch ex As Exception
            MsgBox(ex.Message)
            MsgBox(ex.StackTrace)
        End Try
    End If

End Sub

通过捕获超时异常,我可以立即关闭端口,但是当我再次重新打开 serialPort 时,我必须等待大约 1-2 分钟才能重新打开端口。因为,我是新手,我阅读了文档并发现 serialPort 它是一个非托管资源,因此它不受垃圾收集器的直接控制。

我发现了一个名为 ReleaseCOMObject(o as Object) 的 API 作为 Integer。我试着像那样使用这个 API,

    Dim WithEvents COMPort As New SerialPort

Private Sub ReleaseCOMObject(obj As Object)
    Dim countDown As Int32
    countDown = 1

    While (countDown > 0)
        countDown = System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
    End While

End Sub

Private Sub ClosePort()
    If COMPort.IsOpen Then
        COMPort.DiscardInBuffer()
        COMPort.DiscardOutBuffer()

        Try
            ReleaseCOMObject(COMPort)
            COMPort.Close()

        Catch ex As Exception
            MsgBox(ex.Message)
            MsgBox(ex.StackTrace)
        End Try
    End If

End Sub

API 接受此 COMPort 作为 SerialPort 对象,但是当我发布并运行此代码时,它给了我一个 ArgumentException。这是下面的例外,

An unhandled exception of type 'System.ArgumentException' occurred in mscorlib.dll

Additional information: The object's type must be __ComObject or derived from __ComObject.

我发现还有另一种方法是实现 IDisposable 接口,但是如何在我的表单类中实现这个接口,该接口已经由 Visual Studio 在 Form1.Designer.vb 文件中实现。Visual Studio给出的代码如下,

    'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
    Try
        If disposing AndAlso components IsNot Nothing Then
            components.Dispose()
        End If
    Finally
        MyBase.Dispose(disposing)
    End Try
End Sub

在这方面的任何帮助将不胜感激。

4

0 回答 0