C# Winform freezing on SerialPort.Close

前端 未结 4 1097
闹比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条回答
  •  旧时难觅i
    2021-02-06 01:34

    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!

提交回复
热议问题