问题描述
我有一个应用程序,我从串口读取,一切正常,直到我关闭应用程序.当我单击 [X] 时,应用程序只是挂起,UI:无响应.
I have an app where I read from the serialport, everything goes fine, until I close the app. When I click on the [X] the app simply hangs, the UI: unresponsive.
我从 DataReceived 事件处理程序中的端口读取,并在 FormClosed 发生时关闭端口:
I read from the port in the DataReceived event handler, and I close the port when FormClosed happens:
private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
{
mySerialPort.Close();
}
推荐答案
不是bug.
关闭它时它会挂起的唯一原因是因为在 SerialPort 对象的事件处理程序中,您正在与主线程同步调用(通常通过调用调用).SerialPort 的 close 方法等待触发 DataReceived/Error/PinChanged 事件的 EventLoopRunner 线程终止,但由于您自己的事件代码也在等待主线程响应,因此您遇到了死锁情况.
The only reason it would hang when you close it is because in the event handler of your SerialPort object, you're synchronizing a call with the main thread (typically by calling invoke). SerialPort's close method waits for its EventLoopRunner thread which fires DataReceived/Error/PinChanged events to terminate, but since your own code in the event is also waiting for main thread to respond, you run into a dead lock situation.
错误报告按设计"关闭的原因是因为错误"在您自己的代码中.
The reason the bug report was closed 'as designed' is because the 'bug' is in your own code.
这篇关于C#:使用 Winforms 关闭 SerialPort 的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!