I have a winform program that does some asynchronous IO on a SerialPort. However, I\'m periodically running into an issue with the program freezing on the SerialPo
Workaround by nobugz user from here:
1) add System.Threading.Thread CloseDown; field to form with serial port serialPort1;
2) implement method CloseSerialOnExit() with serialPort1 close steps:
private void CloseSerialOnExit()
{
try
{
serialPort1.DtrEnable = false;
serialPort1.RtsEnable = false;
serialPort1.DiscardInBuffer();
serialPort1.DiscardOutBuffer();
serialPort1.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
3) when you need to close serialPort1 (e.g. on button click) call CloseSerialOnExit() in new thread to avoid hang:
...
CloseDown = new System.Threading.Thread(new System.Threading.ThreadStart(CloseSerialOnExit));
CloseDown.Start();
...
and that's it!