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
The reason it would hang when you close it is because in the event handler of your SerialPort object
You're synchronizing a call with the main thread (typically by calling invoke). SerialPort's close method waits for its EventLoopRunner thread which fires DataReceived/Error/PinChanged events to terminate. but since your own code in the event is also waiting for main thread to respond, you run into a dead lock situation.
solution: use begininvoke instead of invoke: https://connect.microsoft.com/VisualStudio/feedback/details/202137/serialport-close-hangs-the-application
reference: http://stackoverflow.com/a/3176959/146622
EDIT: the Microsoft link is broken as they have retired Connect. try web.archive.org: https://web.archive.org/web/20111210024101/https://connect.microsoft.com/VisualStudio/feedback/details/202137/serialport-close-hangs-the-application
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!
I had a same problem. I solved this problem by using SerialPortStrem library. You can install by Nuget Pageckage Installer.
SerialportStream libary has the following advantages.
After using SerialPortStream library, I hadn't UI freezing problem such as deadlock in WPF. I think the same issue in Windows forms. so, use the SerialPortStream library.
This library is obviously a solution to solve the UI Freezing.
Thank you also for answers. I faced similar issue until today. I used the Andrii Omelchenko solution and helped a lot but not 100%. I saw that the cause for hanging serial port is the reception event handler. Before stopping serial port, uninstall reception event handler.
try
{
serialPort.DtrEnable = false;
serialPort.RtsEnable = false;
serialPort.DataReceived -= serialPort_DataReceived;
Thread.Sleep(200);
if (serialPort.IsOpen == true)
{
serialPort.DiscardInBuffer();
serialPort.DiscardOutBuffer();
serialPort.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}