Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I get data after closing COM port?

Tags:

c#

port

c#-4.0

I have methos that recieve data from opening COM port:

 private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
        {
            SerialPort sp = (SerialPort)sender;

            try
            {
                if (sp.IsOpen)
                {
                    if (sp.BytesToRead > 0)
                    {
                      // Get data
                    }
                 }
              }
}

Also I have method that does connection to COM port:

private void connectPort()
{
SerialPort mySerialPort = new SerialPort(port);
...
}

When I call method that closes port:

mySerialPort.DiscardInBuffer();
mySerialPort.DiscardOutBuffer();
mySerialPort.Close();

After I get data from device still. What is wrong?

like image 600
Ahmed Avatar asked Nov 21 '25 15:11

Ahmed


1 Answers

I don't know for sure, but from the docs it sounds like the fact that the data is being raised from another thread may be buffering and/or lagging a bit behind the actual data (plus it's possible for you to receive data between when you've discarded the buffer and when you close it).

I'd probably unhooking the DataReceivedHandler first, then close the connection, finally discard the data, ex.

mySerialPort.DataReceived -= new SerialDataReceivedEventHandler(DataReceivedHandler);
like image 137
Paul Mrozowski Avatar answered Nov 23 '25 04:11

Paul Mrozowski