0

I am working on vb.net dll, for reading values from a bar code scanner, connected via serial comm port. If the app closes irregularly (i.e.: killed by task manager), the ports stay bound to the app, and i have to restart the whole program. I would like to know if there is a way to somehow release those ports, so i can only restart the crashed app?

Port is initialized:

    Public Sub Init(pPort As String)
        port = New SerialPort(pPort, 9600, Parity.None, 8, StopBits.One)
        port.Handshake = Handshake.None
        port.ReadTimeout = 1000
        port.WriteTimeout = 1000
        port.RtsEnable = True
        port.DtrEnable = True
        port.Open()
    End Sub

Port is closed after use:

    Public Sub Close()
        port.Close()
        port = Nothing
    End Sub

As said before, if the app closes irregularly, it does not close the port. If I try to initialize again i get the error port denied. What can I do in this case?

DontKnow
  • 64
  • 1
  • 8
  • Note that wrapping it in a Try...Finally will not help: [Does the C# “finally” block ALWAYS execute?](https://stackoverflow.com/q/3216046/1115360) (Just in case someone suggests that.) – Andrew Morton Sep 13 '19 at 08:22
  • You could try putting it in a `using block`, although from what Andrew linked and the [documentation](https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/using-statement), it seems like that wouldn't guarantee the port closing either. – AConfusedSimpleton Sep 13 '19 at 08:38
  • Also, i'm wondering: why do you set `port = Nothing`, instead of just calling `port.Dispose`? – AConfusedSimpleton Sep 13 '19 at 08:39
  • I don't think there was a specific reason for that. Anyway - it works perfectly until you kill the app before port was closed. – DontKnow Sep 13 '19 at 08:50
  • It is the job of the operating system to close any devices that were not closed by the app, no help needed. If the workaround is "i have to restart the whole program" then yes, you always have to restart a killed process. So that's surely not what you actually do. A likely cause of trouble like this is anti-malware, blocking access to the process until it has finished its "deep scan". Triggered by it seeing an executable file appearing from seemingly no-where. Temporarily disable it to find out if it is the trouble-maker. – Hans Passant Sep 13 '19 at 10:02

0 Answers0