C#:使用 Winforms 关闭 SerialPort 的正确方法

C#: Proper way to close SerialPort with Winforms(C#:使用 Winforms 关闭 SerialPort 的正确方法)
本文介绍了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 的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)