0

我已经编写了一个服务应用程序,它侦听端口以获取可能通过的任何通信,我们的实验室将运行某个测试,该测试将每隔几个小时左右发送一次串行数据。该服务正在运行几个小时后可以很好地获取数据,然后神秘地停止。系统事件日志说服务意外终止。在应用程序事件日志中,它有一个更具描述性的 .NET 错误,

应用程序:BondTestService.exe 框架版本:v4.0.30319 描述:进程因未处理的异常而终止。异常信息:System.ObjectDisposedException at System.Runtime.InteropServices.SafeHandle.DangerousAddRef(Boolean ByRef) at System.StubHelpers.StubHelpers.SafeHandleAddRef(System.Runtime.InteropServices.SafeHandle, Boolean ByRef) at Microsoft.Win32.UnsafeNativeMethods.GetOverlappedResult(Microsoft .Win32.SafeHandles.SafeFileHandle, System.Threading.NativeOverlapped*, Int32 ByRef, Boolean) 在 System.IO.Ports.SerialStream+EventLoopRunner.WaitForCommEvent() 在 System.Threading.ThreadHelper.ThreadStart_Context(System.Object) 在 System.Threading .ExecutionContext.RunInternal(System.Threading.ExecutionContext,System.Threading.ContextCallback,System.Object,

我正在阅读服务的行为方式以及串行端口的行为方式,所以如果我错了,如果测试之间有 2 小时左右的间隔,请纠正我,服务将假定它没有运行并自行停止?

我还在从串行端口读取缓冲区后读取了我附加到如下所示的字符串构建器对象并对字符串执行我需要的操作,然后串行端口会发生什么它只是保持打开等待下一个值还是我必须关闭它并重新打开它以刷新它?

不确定如何处理这个问题,因为它需要打开等待实验室测试人员在任何给定时间发送他的数据。

Imports System
Imports System.Data.SqlClient
Imports System.IO.Ports
Imports System.Net.Mime
Imports Microsoft.Win32
Imports System.IO
Imports System.Text.RegularExpressions
Imports BondTestService.PI
Imports PCA.Core.Configuration

Public Class Bond
Dim WithEvents serialPort As New IO.Ports.SerialPort
Public Delegate Sub myDelegate()
Public RawString As New System.Text.StringBuilder
Public value As String
Public BondTest As Integer = 10

 #Region "Commport Traffic and Configuration Validations"
 Public Sub StartListening()

    If serialPort.IsOpen Then
        serialPort.Close()
        ErrorLog2(Now.ToString & "Port Closed because StartListening method started over")
    End If

    Try
        With serialPort
            .PortName = Registry.LocalMachine.OpenSubKey("SOFTWARE\Wow6432Node\AUTOLABDEVICESERVICE\bondtest", True).GetValue("commport")
            .BaudRate = CInt(Registry.LocalMachine.OpenSubKey("SOFTWARE\Wow6432Node\AUTOLABDEVICESERVICE\bondtest", True).GetValue("baudrate"))
            If Registry.LocalMachine.OpenSubKey("SOFTWARE\Wow6432Node\AUTOLABDEVICESERVICE\bondtest", True).GetValue("parity") = 0 Then
                .Parity = Parity.None
           End If
            If Registry.LocalMachine.OpenSubKey("SOFTWARE\Wow6432Node\AUTOLABDEVICESERVICE\bondtest", True).GetValue("stopbits") = 1 Then
                .StopBits = StopBits.One
            End If
            .DataBits = CInt(Registry.LocalMachine.OpenSubKey("SOFTWARE\Wow6432Node\AUTOLABDEVICESERVICE\bondtest", True).GetValue("bytesize"))
            .Handshake = Handshake.None
            If Registry.LocalMachine.OpenSubKey("SOFTWARE\Wow6432Node\AUTOLABDEVICESERVICE\bondtest", True).GetValue("RtsControl") = 1 Then
                .RtsEnable = True
            Else
                .RtsEnable = False
           End If
        End With
        serialPort.Open()

        'debug
        'ErrorLog2("Listening to COM 19, SerialPort has been Opened")

    Catch ex As Exception
         ErrorLog2(Now.ToString & ex.tostring)
    End Try
End Sub

Public Function Filelocator() As String

    ' Dim filePath As String = IO.Path.Combine(Application.StartupPath, "bondtest.bat")
    Dim filePath As String = IO.Path.Combine("C:\Program Files (x86)\PIPC\Interfaces\Lab", "BondTest.bat")
    'Dim reader As New System.IO.StreamReader(filePath)
    Dim LineNumber = 4
    Using file As New StreamReader(filePath)
        ' Skip all preceding lines: '
        For i As Integer = 1 To LineNumber - 1
            If file.ReadLine() Is Nothing Then
                ErrorLog2("LineNumber")
            End If
        Next
        ' Attempt to read the line you're interested in: '
        Dim line As String = file.ReadLine()
        If line Is Nothing Then
            ErrorLog2("LineNumber")
        End If
        Return line
    End Using
End Function

Private Sub serialPort_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort.DataReceived
    Try
        If GetBondInterfaceStatus = 1 Then
            UPdateVariable()
        Else
            exit Sub
        End If
    Catch ex As Exception
        Errorlog2(Ex.Tostring)
    End Try
End Sub



#End Region

#Region "String Handling"
Public Sub UPdateVariable()
    With RawString
        .Append(serialPort.ReadLine())
    End With
    try
        ErrorLog2(now.ToString & RawString.ToString)
        InsertTestDataDEBUG(GetRecordID, BondTest, BondTestType.ToUpper.ToString, GetBondPosition(), StringParser(RawString.ToString()), RawString.tostring)
        InsertTestData(GetRecordID, BondTest, BondTestType.ToUpper.ToString, GetBondPosition(), StringParser(RawString.ToString()))
        RawString.Clear()
    Catch ex As Exception
        ErrorLog2(ex.ToString())
    End Try
End Sub

Public Function StringParser(RawString As String)As Double ()
    Dim Moisture = RawString
    Dim pattern As String = "[0-9],"
    Dim regex As New Regex(pattern)
    Dim Counter As Integer = 0
    Dim dblValues(1) As Double
    Dim values As String() = Moisture.Split(New Char() {" "c})


    for i = 0 to values.Count - 1
        if regex.IsMatch(values(i)) Then
            dblValues(Counter) = CDbl(values(i).Substring(0,1))
            Counter = Counter + 1
        Elseif values(i) = "" Then
            continue for
        else
            if Double.TryParse(values(i), dblValues(Counter)) Then
                Counter = Counter + 1 
            End If
        End If

    Next
    Return dblValues
End Function

#End Region

#Region "SQL Statements"
Private Sub InsertTestData(RecordID As Integer, BondTest As Integer, TestType As String, TestPos As Integer, dataArray() As Double)
    Dim InsertQuery As String = ""
    Dim conn As New BondSQLConnection("PaperTests")
   ' Dim TestPos = StartingTestPos + (CInt(dataArray(0)) - 1)

    conn("@RecordID") = RecordID
    conn("@Test") = BondTest
    conn("@TestType") = TestType
    conn("@TestPos") = TestPos
    conn("@TestData") = dataArray(1)
    conn("@TestDateTime") = now.tostring

    InsertQuery = "INSERT INTO PaperTests.dbo.PaperTestValues(ReelRecordID, Test, TestLocation, TestPosition, TestValue, TestTimeStamp) VALUES (@RecordID, @Test, @TestType, @TestPos, @TestData, @TestDateTime)"
    Try
        conn.ExecuteNonQuery(InsertQuery)
        IncrementTestPosition
    Catch ex As Exception
        ErrorLog2(ex.ToString())
    End Try

End Sub

Private Sub InsertTestDataDEBUG(RecordID As Integer, BondTest As Integer, TestType As String, TestPos As Integer, dataArray() As Double, rawString As String)
    Dim InsertQuery As String = ""
    Dim conn As New BondSQLConnection("PaperTests")

    conn("@RecordID") = RecordID
    conn("@Test") = BondTest
    conn("@TestType") = TestType
    conn("@TestPos") = TestPos
    conn("@TestData") = dataArray(1)
    conn("@RawString") = rawString
    conn("@TestDateTime") = now.tostring

    InsertQuery = "INSERT INTO PaperTests.dbo.InterfaceTesting(ReelRecordID, Test, TestLocation, TestPosition, TestValue, TestTimeStamp, RawValue) VALUES (@RecordID, @Test, @TestType, @TestPos, @TestData, @TestDateTime, @RawString)"
    Try
        conn.ExecuteNonQuery(InsertQuery)
    Catch ex As Exception
        ErrorLog2(ex.ToString())
    End Try

End Sub

Private Sub IncrementTestPosition()
    Dim tempPosition As Integer = GetBondPosition()
    Dim FrontOriginalMax = 5
    Dim CenterOriginalMax = 15
    Dim BackOriginalMax = 25
    Dim FrontRetestOrWinderMax = 10
    Dim CenterRetestOrWinderMax = 20
    Dim BackRetestOrWinderMax = 30

    If tempPosition = FrontOriginalMax Then
        tempPosition = 11
    else if tempPosition = CenterOriginalMax Then
        tempPosition = 21
    else if tempPosition = BackOriginalMax Then
        tempPosition = 1
    Else If tempPosition = FrontRetestOrWinderMax then
        tempPosition = 1
    Else If tempPosition = CenterRetestOrWinderMax then
        tempPosition = 1
    Else If tempPosition = BackRetestOrWinderMax then
        tempPosition = 1
    else 
        tempPosition = tempPosition + 1
    End If
    SetBondPosition(tempPosition.tostring)
End Sub

#End Region

#Region "Get PiValues"
Private Function GetRecordID() As Int64
    Dim RecordID As Int32 = 0
    Try
        Dim piserver As New PIServer("valpi", "piadmin", "fatb0y",True)
        RecordID = piserver.GetCurrentValue("PAPERLAB:PaperLabReelSelected")
    Catch ex As Exception
        ErrorLog2(ex.ToString())
    End Try
    Return RecordID
End Function

Private Function GetBondPosition() As Int64
    Dim BondPos As Int32 = 0
    Try
        Dim piserver As New PIServer("valpi", "piadmin", "fatb0y",True)
        BondPos = CInt(piserver.GetCurrentValue("PAPERLAB:SBOND.POS"))
    Catch ex As Exception
        ErrorLog2(ex.ToString())
    End Try
    Return BondPos
End Function
Private Sub SetBondPosition(pos As String) 
    Try
        Dim piserver As New PIServer("valpi", "piadmin", "fatb0y",True)
       piserver.WriteValue("PAPERLAB:SBOND.POS", pos)
    Catch ex As Exception
        ErrorLog2(ex.ToString())
    End Try
End Sub

Private Function BondTestType() As String
    Dim TestType As String = ""
    Try
        Dim piserver As New PIServer("valpi", "piadmin", "fatb0y",True)
        TestType = piserver.GetCurrentValue("M1:BOND.TYPE")
    Catch ex As Exception
        ErrorLog2(ex.ToString())
    End Try
    Return TestType
End Function

Private Function BondReelLoc() As String
    Dim ReelLoc As String = ""
    Try
        Dim piserver As New PIServer("valpi", "piadmin", "fatb0y",True)
        ReelLoc = piserver.GetCurrentValue("M1:BOND.ReelLoc")
    Catch ex As Exception
        ErrorLog2(ex.ToString())
    End Try
    Return ReelLoc
End Function

Private Function GetBondInterfaceStatus() As Integer
    Dim Status As Integer = 0
    Try
        Dim piserver As New PIServer("valpi", "piadmin", "fatb0y",True)
        Status = CInt(piserver.GetCurrentValue("PAPERLAB:BOND_INTERFACE.S"))
    Catch ex As Exception
        ErrorLog2(ex.ToString())
    End Try
    Return Status
End Function

#End Region

#Region "Debug"

    Private Sub ErrorLog(RecordID As Int32, BondTest As Integer, ReelLoc As String, TestType As String, StartingTestPos As Integer, dataArray() As Double)
    Dim SavePath As String = "C:\Program Files (x86)\PIPC\Interfaces\Lab"
    Dim NameOfFile As String = "BondTest Debug File"
    Dim TestPos = StartingTestPos + (CInt(dataArray(0)) - 1)

    If System.IO.File.Exists(SavePath & "\" & NameOfFile & ".txt") Then
        Using sw As StreamWriter =  New StreamWriter(SavePath & "\" & NameOfFile & ".txt", True)

          '  For i = 0 To dataArray.Count -1 
                sw.WriteLine(" ")
                sw.WriteLine(RecordID & "   " & BondTest & "    " & ReelLoc & "    " & TestType  & "   " & TestPos & "   " & dataArray(1).ToString)
              '  TestPos = TestPos + 1
          '  Next
        End Using
    else
        File.Create(SavePath & "\" & NameOfFile & ".txt").Dispose()
        Using sw As StreamWriter = File.CreateText(SavePath & "\" & NameOfFile & ".txt")
            'For i = 0 To dataArray.Count -1 
                sw.WriteLine(" ")
                sw.WriteLine(RecordID & "   " & BondTest & "    " & ReelLoc & "    " & TestType  & "   " & TestPos & "   " & dataArray(1).ToString)
              '  TestPos = TestPos + 1
            'Next
        End Using
    End If
End Sub

Private Sub ErrorLog2(dataArray as string)
    Dim SavePath As String = "C:\Program Files (x86)\PIPC\Interfaces\Lab"
    Dim NameOfFile As String = "BondTest Debug File"
   ' Dim TestPos = StartingTestPos

    If System.IO.File.Exists(SavePath & "\" & NameOfFile & ".txt") Then
        Using sw As StreamWriter = New StreamWriter(SavePath & "\" & NameOfFile & ".txt", True)
                sw.WriteLine(" ")
                sw.WriteLine(dataArray)
        End Using
    else
        File.Create(SavePath & "\" & NameOfFile & ".txt").Dispose()
        Using sw As StreamWriter = File.CreateText(SavePath & "\" & NameOfFile & ".txt")
                sw.WriteLine(" ")
                sw.WriteLine(dataArray)
        End Using
    End If
End Sub

#End Region

这是错误的屏幕截图:

错误

提前致谢

4

2 回答 2

1

通常,在 .NET 中打开串行端口后,它会保持打开任意时间。我编写了几个 .NET 应用程序,串行端口使用数月或数年而无需重新启动应用程序或计算机,并且它们运行良好。

根据您发布的异常信息,该串行端口似乎已被处理。有几个可能的原因。

  1. 使用错误的驱动程序或硬件会断开您的串行端口。我一直在使用许多 USB-to-RS232 转换器,其中一些有坏的驱动程序,所以有时端口被随机断开ObjectDisposedException并被抛出。在早期的 Windows 版本 (XP) 中,操作系统甚至“蓝屏”。ObjectDisposedException是有关抛出这种情况的更多信息。

这是 SerialPort 的一个已知问题。设备移除会在它使用的后台线程中导致无法捕获的异常 (WaitForCommEvent)。唯一的解决方案是不使用 SerialPort 或创建一个 .config 文件,将未处理的异常捕获模式放回 .NET 1.1 行为。

  1. 手动断开 RS232 转换器的 USB 电缆。如果这样做,大多数驱动程序通常会断开与串行端口的所有句柄,并且 .NET 会抛出ObjectDisposedException.

  2. 如果使用 USB 转 RS232 转换器,还要检查 USB 端口上的电源管理设置。能源管理尝试在连接转换器的 USB 设备上取消选中此选项。

  3. 代码中的 SW 错误。

始终建议(特别是如果使用转换器)尝试更多类型的转换器,以确保硬件设备/驱动程序没有问题。

于 2018-09-20T03:37:37.937 回答
0

更新:正如蒂米所说,垃圾收集处理了连接。所以我将对象声明为类中的共享变量

Shared Dim WithEvents serialPort as IO.Ports.SerialPort

在 OnStart 方法中,我将它作为一个新的串行端口启动并继续运行。没有抛出任何错误,因为垃圾收集不会处理它。希望这可以帮助遇到类似问题的人。

于 2018-10-18T14:09:59.633 回答