Author Topic: C# program crashes closing the serial port  (Read 26741 times)

scott_hansen

  • Member
  • ***
  • Posts: 1
C# program crashes closing the serial port
« on: August 04, 2010, 10:44:48 am »
Hi everyone,

I am working on a C#  WinForms program using VS 2008 express that reads serial port data from a marine GPS unit.  The program has a combo box to select the com port, a START button event (sets the port, starts reading the data) and a STOP button event that displays the averages of the GPS data.  I use the serial port data received event to parse and average the data.

The program reads, parses and displays the data correctly.  After I display the average data in the STOP button event code, I don't want to receive data anymore so I close the port.  When I close the port directly by calling "Close()", the program crashes.  I saw on-line that to close the port from a Window Form that you need to start a new thread and close the port in the thread.  I call the function CloseSerialPortThread().  When I call this function, it still crashes.

I know the program still reads the data in the STOP button event code.  I change the label lblStatVal text to "data read stopped".  Since the port is still open, the label text changes to "GGA Data Received".

Finally, I have a form closing event.  When I try to close the port directly, the program hangs up or crashes.  I then called CloseSerialPortThread() and the program exits without crashing or "hanging up".  I have attached the Form source code.

Thank you for your help.



[attachment deleted by admin]

Jan Axelson

  • Administrator
  • Frequent Contributor
  • *****
  • Posts: 3033
    • Lakeview Research
Re: C# program crashes closing the serial port
« Reply #1 on: August 04, 2010, 12:25:14 pm »
I've used this without problems:

internal void CloseComPort( SerialPort portToClose )
{
  object transTemp0 = portToClose;
  if (  !(  transTemp0 == null ) )
  {                     
    if ( portToClose.IsOpen )
    {                         
      portToClose.Close();   
    }
  }               
}

Jan