Results 1 to 23 of 23

Thread: VB.NET Serial Port Help - Issues with open and closing then reopening and closing.

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Dec 2014
    Posts
    82

    VB.NET Serial Port Help - Issues with open and closing then reopening and closing.

    I have constant data coming into a serial port. My program is able to display the data coming into the serial port using a textbox.
    I have a Open pushbutton that when pressed starts receiving the data and display it in the textbox.

    My issue is that I need to be able to Open and Close the port at will however many times.

    It seems there are problems when opening and closing the port and reopening and closing the port.
    It may open and close 2 or 3 times but then after that if you try to open you get an error such as this

    "An unhandled exception of type 'System.IO.IOException' occurred in System.dll
    Additional information: The I/O operation has been aborted because of either a thread exit or an application request."

    I can open the port and display the constant data in a textbox for days. The issue is open and closing and reopening and closing.

    Does anyone have some code that works or a way to remedy these issues.

  2. #2
    Sinecure devotee
    Join Date
    Aug 2013
    Location
    Southern Tier NY
    Posts
    6,116

    Re: VB.NET Serial Port Help - Issues with open and closing then reopening and closing

    My first question is do you have to close the port?
    I can understand closing the port if you want to start another program that will use the port, but if not, then it would seem best to just set a flag to stop processing the data received ("dump it on the floor") until you want to start processing it again.
    Since there are multiple threads involved in using the SerialPort object (I'm assuming you're using the SerialPort class), generally with a new thread created with every receive event, and exited once the receive event has been processed, if you possibly open and close repeatedly without proper clean up and disposing of resources (and I don't know what may constitute "proper clean up and disposing" with the SerialPort object at this point), I could see the possibility of a thread issue. I don't currently have a setup where I could do a test to see if I could replicate your issue (I have a couple of applications that use serial ports, and they are just kicked off and stay connected for months, only disconnecting if power goes out). Since you also don't have an issue with running for days on end, is why I'm suggesting that perhaps you just want to change the flow of data, rather than break the connection.
    But, if you really need to break the connection because you need the port for something else, then perhaps I can gather some hardware to set up a test situation to see if I can recreate the problem and investigate "proper" closing/opening methods.
    What baud rate are you running at?
    I assume you're not using any kind of handshake.

  3. #3
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Pointless Forest 38.517,-92.023
    Posts
    9,302

    Re: VB.NET Serial Port Help - Issues with open and closing then reopening and closing

    My guess would be that the serial port is handling one of its events when you attempt to close it. To ascertain if the port will fail on close if there is no activity I wrote the following test:

    Code:
    Public Class Form1
    
        Dim sp As New IO.Ports.SerialPort("COM1")
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Static openCT As Integer = 1
            If sp.IsOpen Then
                sp.Close()
                Debug.WriteLine("CLOSED")
            Else
                Try
                    sp.Open()
                    Debug.WriteLine("OPENED " & openCT.ToString("n0"))
                    openCT += 1
                Catch ex As Exception
                    Stop
                End Try
            End If
        End Sub
    
        Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
            Button2.Enabled = False
            Dim t As New Threading.Thread(AddressOf doTest)
            t.IsBackground = True
            t.Start()
        End Sub
    
        Private Sub doTest()
            For x As Integer = 1 To 2000
                Me.Invoke(Sub()
                              Button1.PerformClick()
                          End Sub)
                Threading.Thread.Sleep(0)
            Next
    
            Me.Invoke(Sub()
                          Button2.Enabled = True
                      End Sub)
        End Sub
    End Class
    The test never failed.

    I have seen the error when attempting to close if one of the events was active.
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  4. #4

    Thread Starter
    Lively Member
    Join Date
    Dec 2014
    Posts
    82

    Re: VB.NET Serial Port Help - Issues with open and closing then reopening and closing

    Yes, I need the flexability of opening and closing the port at will. I don't see why .net has an issue with this. To me you should be able to open and close the port at anytime and however many times like some other controls. There should be a clean way of doing it. Its not an issue in VB6 using MSComm.

    I am using a picture box control as an indicator for Open and Close buttons. Red when close button pressed and Green when open button pressed. I observed that when close is pressed sometimes the indicator stays green meaning the port does not close with a SeriaPort.Close. When close is pressed I issue a serialport.DiscardInBuffer followed by a serialport.Close

    Yes I am using the SerialPort Class.

  5. #5
    Sinecure devotee
    Join Date
    Aug 2013
    Location
    Southern Tier NY
    Posts
    6,116

    Re: VB.NET Serial Port Help - Issues with open and closing then reopening and closing

    Have you read the following http://zachsaw.blogspot.com/2010/07/...port-woes.html and tried the work around at the end?

    A vb.net version of the C# code is found in post #3, here http://forums.codeguru.com/showthrea...s-in-a-Service

    Haven't tried any of this out myself.
    Last edited by passel; Jan 22nd, 2015 at 05:00 PM.

  6. #6

    Thread Starter
    Lively Member
    Join Date
    Dec 2014
    Posts
    82

    Re: VB.NET Serial Port Help - Issues with open and closing then reopening and closing

    Yes I did read that. The workaround sample code is in c#. My experience is only in Fortran, Cobol, Ada, Pascal, VB and VB.Net no C#

  7. #7
    Sinecure devotee
    Join Date
    Aug 2013
    Location
    Southern Tier NY
    Posts
    6,116

    Re: VB.NET Serial Port Help - Issues with open and closing then reopening and closing

    Added another link (to post #5) where someone did a vb.net version.
    (had to read down through a lot of the comments to find comment from GremlinSA, May 23, 2013).

  8. #8
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Pointless Forest 38.517,-92.023
    Posts
    9,302

    Re: VB.NET Serial Port Help - Issues with open and closing then reopening and closing

    Using the code I posted can you confirm that this happens. My suspicion is that the real code is processing an event on another thread when the close is attempted.
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  9. #9

    Thread Starter
    Lively Member
    Join Date
    Dec 2014
    Posts
    82

    Re: VB.NET Serial Port Help - Issues with open and closing then reopening and closing

    dbasnett I do not see where the sub doTest() is called in the rest of your code.

  10. #10

    Thread Starter
    Lively Member
    Join Date
    Dec 2014
    Posts
    82

    Re: VB.NET Serial Port Help - Issues with open and closing then reopening and closing

    I am still looking for any assistance or info on opening and closing serial ports at will.

    Thinking about maybe using the Windows API for serial communications or using MSComm in .NET
    since the serial port class is flakey in .NET for the lack of a better word. I don't see how Microsoft
    has not fixed these issues with the serial port.

    Its hit and miss sometimes I can open and close the port 2, 3, 4 times before getting

    "An unhandled exception of type 'System.IO.IOException' occurred in System.dll
    Additional information: The I/O operation has been aborted because of either a
    thread exit or an application request.

    Sometimes I get these errors as soon as SerialPort.Open() is executed.

  11. #11
    Sinecure devotee
    Join Date
    Aug 2013
    Location
    Southern Tier NY
    Posts
    6,116

    Re: VB.NET Serial Port Help - Issues with open and closing then reopening and closing

    Well you could try to figure out how to use the API or a COM object instead, but it should only take a couple of minutes to try the PortTester.PortFixer Class to see if it would work, then you wouldn't have to change the rest of your existing code.

    I don't have the problem and still haven't set up a test case, but I did try the change out anyway, just to see if there were any issues with it breaking the application or not compiling.
    I just opened an existing project that uses a serial port, selected to add a class module from the Project menu, named it and then when the code window popped up, just replaced the code with the code from the link above.
    Looked for where I opened the port and just added the single line in front of where I open the port and ran the application, and it still works fine, so the new class didn't break anything. The only thing is you won't get that exception any longer for the messed up Microsoft reason.
    Code:
      Public Sub ListModeInitialize()
        Try
          SerialPortTester.SerialPortFixer.Execute("COM10")  'Added to prevent a MS coding error exception from the SerialPort class.
          comPort.Open()
    '...
    p.s. Perhaps I spoke too soon. The way I'm opening the port, doesn't seem to be working any longer. There is no error, but the communication isn't going. I'll have to investigate a little further.
    p.p.s. Nope, it did work fine. It is just I went between two different machines, and they don't have the same com ports, and I didn't bind to the correct port when I moved the code to the other machine.

    Good luck to you when you get a chance to try it. I would hope MS will take notice since the person who did the work around has pretty much debugged and identified what MS has to fix in their implementation.
    Last edited by passel; Jan 23rd, 2015 at 07:53 PM.

  12. #12

    Thread Starter
    Lively Member
    Join Date
    Dec 2014
    Posts
    82

    Re: VB.NET Serial Port Help - Issues with open and closing then reopening and closing

    I am gone for the day from work but I will be in tomorrow and I will try it. Thanks to everyone for assisting.

  13. #13
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Pointless Forest 38.517,-92.023
    Posts
    9,302

    Re: VB.NET Serial Port Help - Issues with open and closing then reopening and closing

    In the button click handler a thread is created to open and close the port several times.
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  14. #14

    Thread Starter
    Lively Member
    Join Date
    Dec 2014
    Posts
    82

    Re: VB.NET Serial Port Help - Issues with open and closing then reopening and closing

    dbasnett I put 2 push buttons on my app to handle the code you posted. My app looks at Com6 so I changed your line of code to
    Dim sp As New IO.Ports.SerialPort("COM6")

    What button do I press and when. What am I looking for.

  15. #15
    Sinecure devotee
    Join Date
    Aug 2013
    Location
    Southern Tier NY
    Posts
    6,116

    Re: VB.NET Serial Port Help - Issues with open and closing then reopening and closing

    I don't know that you need it. The code will open and close the serial port a thousand times in a short period.
    You start it by pressing button2.
    If the serial port is not active (no one is transmitting to it), it should open and close the port a thousand times without issue.
    If someone is transmitting on the serial port, you will probably get an exception during the loop at some point.

    The point of the code is just to open and close the port many times by code to see if opening and closing of the port is inherently a problem, or only when closing and opening a port while the port is actively receiving data.

    In your case, it seems like the issue is fairly repeatable, so you probably don't need test code to hammer opening and closing.
    But, the assumption is, if you run your code so you have active data coming in, and you run the test code (pushing button2), so that it rapidly opens and closes the port a thousand times, and you don't get the exception, then the "fix" worked.

  16. #16

    Thread Starter
    Lively Member
    Join Date
    Dec 2014
    Posts
    82

    Re: VB.NET Serial Port Help - Issues with open and closing then reopening and closing

    I thought so. I did that. I was just asking to be sure.

    Ok, I run my app and hit button 2 and get an error in the doTest() sub at the Me.Invoke(Sub() Button1.PerformClick() End Sub).

    Error says
    Name:  serialerror1.jpg
Views: 3671
Size:  32.8 KB

  17. #17

    Thread Starter
    Lively Member
    Join Date
    Dec 2014
    Posts
    82

    Re: VB.NET Serial Port Help - Issues with open and closing then reopening and closing

    I change the loop from 2000 to 20 and it error out at x = 2 in the for loop.

  18. #18

    Thread Starter
    Lively Member
    Join Date
    Dec 2014
    Posts
    82

    Re: VB.NET Serial Port Help - Issues with open and closing then reopening and closing

    Ok passel I used the PortTester.PortFixer Class. In my app I have a start button to start receiving com port data and a stop button to stop receiving com port data. When I press start I start receiving data and my picture box indicator turns green to show I have the port open and I am receiving data problem is that sometimes when I click on the stop button it should turn the picture box red indicating that the port is closed and data is no longer being received however sometimes it stays green when I hit stop and the port remains open even though it should close.

  19. #19
    Sinecure devotee
    Join Date
    Aug 2013
    Location
    Southern Tier NY
    Posts
    6,116

    Re: VB.NET Serial Port Help - Issues with open and closing then reopening and closing

    Without any code, we can't possibly guess at how you are closing the port and how you are checking the status to know if it is closed or not, and how you're setting the picturebox color to reflect that it is closed or not.

  20. #20

    Thread Starter
    Lively Member
    Join Date
    Dec 2014
    Posts
    82

    Re: VB.NET Serial Port Help - Issues with open and closing then reopening and closing

    How I open the com port

    Private Sub btnStart_Click(sender As Object, e As EventArgs) Handles btnStart.Click
    SerialPortTester.SerialPortFixer.Execute("COM6")
    OpenComPort()
    End Sub

    Private Sub OpenComPort() '(ByVal sender As System.Object, ByVal e As System.EventArgs)
    'device params
    With SerialPort1

    ''.ParityReplace = &H3B 'replace ";" when parity error occurs
    .PortName = "Com6" 'cboComPort.Text
    .BaudRate = 9600 'CInt(cboBaudRate.Text)
    .Parity = IO.Ports.Parity.None
    .DataBits = 8
    .StopBits = IO.Ports.StopBits.One
    ''.Handshake = IO.Ports.Handshake.None
    ''.RtsEnable = False
    ''.ReceivedBytesThreshold = 1 'threshold: one byte in buffer > event is fired
    ''.NewLine = vbCr 'CR must be the last char in frame. This terminates the SerialPort.readLine
    ''.ReadTimeout = 10000

    End With

    ' check whether device is avaiable:
    Try
    SerialPort1.Open()
    comOpen = SerialPort1.IsOpen
    Catch ex As Exception
    comOpen = False
    MsgBox("Error Open: " & ex.Message)
    picOpen1.BackColor = Color.Red
    End Try

    If comOpen Then
    picOpen1.BackColor = Color.Green
    ''cboComPort.Enabled = False
    ''cboBaudRate.Enabled = False
    End If
    End Sub

  21. #21

    Thread Starter
    Lively Member
    Join Date
    Dec 2014
    Posts
    82

    Re: VB.NET Serial Port Help - Issues with open and closing then reopening and closing

    How I close the com port

    Private Sub btnStop_Click(sender As Object, e As EventArgs) Handles btnStop.Click
    CloseComPort()
    End Sub

    Private Sub CloseComPort() '(ByVal sender As System.Object, ByVal e As System.EventArgs)
    Using SerialPort1
    If (Not (SerialPort1 Is Nothing)) Then
    If SerialPort1.IsOpen Then
    Do While (SerialPort1.BytesToWrite > 0)
    Loop
    End If
    End If
    End Using


    comOpen = False
    picOpen1.BackColor = Color.Red
    picDataReceived1.BackColor = Color.Gray

    End Sub

  22. #22
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Pointless Forest 38.517,-92.023
    Posts
    9,302

    Re: VB.NET Serial Port Help - Issues with open and closing then reopening and closing

    The code I posted was supposed to be ran in a new project. The intent was to prove (or not prove) that the problem wasn't with opening an closing. All you should have to do is change the port name.

    I suspect the code will run without problems.
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  23. #23

    Thread Starter
    Lively Member
    Join Date
    Dec 2014
    Posts
    82

    Re: VB.NET Serial Port Help - Issues with open and closing then reopening and closing

    OK. I think I have it solved.

    Passel I included the PortTester.PortFixer Class in my application and still had some issues. However I changed this line in my code in the DataReceived event

    From
    Me.Invoke(New EventHandler(AddressOf DoUpdate))

    To
    Me.BeginInvoke(New EventHandler(AddressOf DoUpdate))

    I have been able to run my application then open and close the com port about 15 times consecutively.

    Thanks to everyone for the assistance with this issue.
    Last edited by djsnts; Jan 26th, 2015 at 09:33 AM. Reason: spelling

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width