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 的正确方法


- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01