C# Winform freezing on SerialPort.Close

前端 未结 4 1121
闹比i
闹比i 2021-02-06 01:14

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

4条回答
  •  佛祖请我去吃肉
    2021-02-06 01:36

    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);
            }
    

提交回复
热议问题