Nic
Nic

Reputation: 93

Serial port auto close hangs

I'm trying to open and close a serial port with one button click event. But it always hangs whenever it hits the serialport.close part. Why?

 private void btn_auto_Click(object sender, EventArgs e)
    {
            try
            {
                myport = new SerialPort();
                myport.BaudRate = 9600;
                myport.PortName = cb_portname.Text;
                myport.Open();
                myport.DataReceived += new SerialDataReceivedEventHandler(myport_DataReceived2);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
            }
        }
    }

void myport_DataReceived2(object sender, SerialDataReceivedEventArgs e)
    {
        try
        {
            in_data = myport.ReadLine();
            this.Invoke(new EventHandler(displaydata_event2));
        }
        catch (Exception)
        {

        }
    }

private void displaydata_event2(object sender, EventArgs e)
    {
        string inStr;
        inStr = in_data;

        if (inStr.Length == 18)
        {
            int indexOfSpace = inStr.IndexOf(':');
            string Temp = inStr.Substring(indexOfSpace + 1);

            txtData2.Text = Temp;
        }

        if (txtData2.Text != "")
        {
            myport.Close();   //===== ALWAYS HANGS AT THIS PART =====
            MessageBox.Show("STOPPED");
        }

    }

So, it always hangs under the if txtData2 not equals part. Is it due to it requires a button action for a serialport to close and it cannot auto close? Thanks in advance.

Upvotes: 1

Views: 878

Answers (1)

Peter Duniho
Peter Duniho

Reputation: 70701

Looking at the source code for the SerialPort class, and in particular for its associated SerialStream class, it appears that the Close() method will block waiting for handlers of any raised events to complete.

Your handling of the received data seems a bit suspect in any case, in that you only even bother to look at the received data if the received line is exactly 18 characters long, as well as in that you are using an instance field to pass data between two methods (very bad idea).

But most likely the biggest issue here, the one causing the deadlock, is that you are calling the SerialPort.Close() method before the DataReceived event handler has completed. Don't do that. Fix your code so that handling received data is a completely independent operation from actually closing the serial port, so that the former can complete before you attempt the latter.

Upvotes: 1

Related Questions