"The I/O operation has been aborted because of either a thread exit or an application request" 断开串口

"The I/O operation has been aborted because of either a thread exit or an application request" on disconnecting serial

我正在编写一个程序来从串行读取数据并显示它。有时(不是每次)当我断开串口时它会崩溃,异常 The I/O operation has been aborted because of either a thread exit or an application request。 (我想这里有问题,即使它不是每次都会发生)。

这是我阅读连载的方式:

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

我做错了什么?

您在事件处理程序中从串口读取数据。来自 SerialPort.ReadLine():

By default, the ReadLine method will block until a line is received.

所以当你关闭串口的时候,有可能你还在等待接收线路。但是如果端口关闭你就收不到数据,所以抛出一个Exception 因为不可能再收到一行。

我已经这样改了,现在可以用了。

try
{
    read = _serialPort.ReadLine().Replace(".", ",").Split('\r')[0];
}
catch (System.IO.IOException error)
{
    return;
}
catch (System.InvalidOperationException error)
{
    return;
}

发生了 2 种错误,IOException 和问题标题上的消息,以及 InvalidOperationException,消息 "The port is closed"。在这两种情况下,我们只会 return 而不会处理数据。

我不确定这是不是应该做的,但无论如何,它有点管用。

当您在 SerialDataReceivedEventHandler 中从 SerialPort.ReadLine() 获取数据时 你必须检查串行端口是否打开。

例如:

if (!_serialPort.IsOpen)
{
  return;
}

string read = _serialPort.ReadLine().Replace(".", ",").Split('\r')[0];