C#: Proper way to close SerialPort with Winforms(C#:使用 Winforms 关闭 SerialPort 的正确方法)
问题描述
我有一个应用程序,我从串口读取,一切正常,直到我关闭应用程序.当我单击 [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 的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C#:使用 Winforms 关闭 SerialPort 的正确方法
基础教程推荐
- 将数据集转换为列表 2022-01-01
- 如果条件可以为空 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
