C#:适当的方法来关闭与的WinForms的SerialPort [英] C#: Proper way to close SerialPort with Winforms

查看:450
本文介绍了C#:适当的方法来关闭与的WinForms的SerialPort的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有,我从阅读的serialport一个应用程序,一切顺利,直到我关闭应用程序。当我点击[X]应用程序只是挂,用户界面:反应迟钝



我从DataReceived事件检索处理程序的端口读,我关闭端口时, FormClosed情况:

 私人无效MainForm_FormClosed(对象发件人,FormClosedEventArgs E)
{
mySerialPort.Close( );
}


解决方案

这不是一个错误。



当您关闭它是因为在你的SerialPort对象的事件处理程序,你用同步主线程调用它会挂起的唯一原因(通常通过调用调用)。的SerialPort的close方法等待其EventLoopRunner线程时触发DataReceived /错误/ PinChanged事件终止,但由于在事件您自己的代码也在等待主线程响应,你碰到一个死锁情况。



错误报告被关闭作为设计的的原因是因为错误是你自己的代码。


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.

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();
    }

解决方案

It's not a bug.

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆