【发布时间】:2015-12-19 10:22:38
【问题描述】:
我正在编写一个程序来从串行读取数据并显示它。有时(不是每次)当我断开串行连接时它会崩溃,但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.Close() 调用与 DataReceived 事件处理程序互锁。当事件处理程序仍在运行时,Close() 无法进行。水晶球说您实际上用手猛拉 USB 连接器。永远不要这样做,始终通过安全删除硬件托盘图标。不清楚为什么你这样做,拔掉插头永远不会解决死锁。而是修复你的事件处理程序,永远不要调用 Invoke(),总是 BeginInvoke()。另外请记住,如果您不设置 ReadTimeout 属性,通信不可靠或中断,ReadLine() 是有风险的。
-
@HansPassant 不,我没有拔掉它,我只是在我的应用程序中多次点击连接/断开串行按钮,最终发生异常
-
@HansPassant 并且我没有在我的处理程序中使用 Invoke() ,我只使用 BeginInvoke 在主线程中运行一些代码,但无论如何,如果我要注释掉这段代码,例外是还是扔了。
标签: c# exception exception-handling serial-port