Reputation: 4670
I am writing a program to read data from serial and display it. Sometimes (not every time) it crashes when I disconnect serial with the exception The I/O operation has been aborted because of either a thread exit or an application request
. (I guess something is wrong here even it happens not every time).
Here is how I am reading serial:
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
// this line below is where the exception is
string read = _serialPort.ReadLine().Replace(".", ",").Split('\r')[0];
}
// clicking on a button opens/closes serial
private void button1_Click(object sender, EventArgs e)
{
if (isSerialConnected)
disconnectSerial();
else
connectSerial();
}
public void connectSerial()
{
_serialPort.PortName = serialCombobox.SelectedItem.ToString();
_serialPort.BaudRate = 9600;
_serialPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(this.serialPort1_DataReceived);
_serialPort.Open();
serialCombobox.Enabled = false;
connectSerialButton.Text = "disconnect";
isSerialConnected = true;
}
public void disconnectSerial()
{
_serialPort.Close();
serialCombobox.Enabled = true;
connectSerialButton.Text = "connect";
isSerialConnected = false;
}
What am I doing wrong?
Upvotes: 2
Views: 20366
Reputation: 13
When you get data from SerialPort.ReadLine()
in your SerialDataReceivedEventHandler
you must check serial port is open.
For example:
if (!_serialPort.IsOpen)
{
return;
}
string read = _serialPort.ReadLine().Replace(".", ",").Split('\r')[0];
Upvotes: 0
Reputation: 4670
I've changed it this way, and now this kinda works.
try
{
read = _serialPort.ReadLine().Replace(".", ",").Split('\r')[0];
}
catch (System.IO.IOException error)
{
return;
}
catch (System.InvalidOperationException error)
{
return;
}
There were 2 kind of errors that happened, IOException with the message that is on the question's title, and InvalidOperationException, with the message "The port is closed". In both cases we'll just return and not process the data.
I'm not sure that it is the way it should be done, but anyway, it kinda works.
Upvotes: 3
Reputation: 15232
You read data from the serial port in an event handler. From SerialPort.ReadLine():
By default, the ReadLine method will block until a line is received.
So when you close the serial port, it is possible you are still waiting to receive a line. But you cannot receive data if the port is closed, so an Exception is thrown because it is not possible any more to receive a line.
Upvotes: 3