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 的正确方法
基础教程推荐
- 如何激活MC67中的红灯 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01