串行端口意外关闭
我有一个 C# 应用程序,它使用 SerialPort 对象在另一台具有蓝牙功能的计算机上运行的应用程序的另一个副本之间建立连接。该程序相当频繁地从主机写出一些 ASCII 数据,然后由远程计算机接收。这个过程进行得相当顺利(尽管并非没有一些不必要的不稳定,但这不是这个问题的目的)。
一切进展顺利,直到我切换形式。该应用程序具有三种主要形式。切换表单时,隐藏旧表单并显示新表单。用户使用 form2 或 form3 上的 [X]
工具栏按钮关闭这些表单并返回到 form1 (不是我的设计决定。该项目基于 VB6 应用程序,我没有太多回旋余地更改其功能)。
当我从 form1 转到 form2 时,serialPort 突然开始报告它已关闭。但是...它继续发送数据。也就是说,直到我切换回 form1,此时我收到一个 InvalidOperationException
告诉我串行端口已关闭,并且无法写入。 SerialPort 对象是私有的,form1 是唯一接触它的表单。
为了确保我没有意外地在某个地方关闭它,我注释掉了项目中的每一个 serialPort.Close();
行,并且我仍然得到相同的结果错误。有什么东西导致端口关闭(或报告它已关闭),我不知道是什么。此外,我无法重新打开它,因为它告诉我该端口当前正在使用中。
我对蓝牙或网络一无所知,所以这都是我在谷歌身边摸索的结果。也许这里有人足够了解 SerialPort 类的细微差别,知道我做错了什么。
感谢所有能够提供帮助的人。
I have a C# application that uses the SerialPort object to establish a connection between another copy of the application running on another machine with BlueTooth capabilities. The program fairly constantly writes out some ascii data from the main machine, which is then received by the remote machine. The process goes fairly nicely (though not without some unwanted choppiness, but that's not what this question is about).
It goes nicely, that is, until I switch forms. The application has three main forms. When forms are switched, the old form is hidden and the new one is shown. The user uses the [X]
toolbar button on form2 or form3 to close those forms and return to form1 (not my design decision. The project is based on a VB6 application and I haven't gotten much leeway to change its functionality).
When I go from form1 to form2, the serialPort suddenly starts reporting that it's closed. But... it continues to send data. That is, until I switch back to form1, at which point I get an InvalidOperationException
telling me that the serialPort is closed, and can't write. The serialPort object is private, and form1 is the only form that touches it.
Just to be sure that was I wasn't going through and closing it somewhere on accident, I commented out every single serialPort.Close();
line in the project, and I'm still getting the same error. Something is causing the port to close (or report that it's closed) and i have no idea what. Furthermore, I can't open it back up, because it tells me that the port is currently in use.
I don't really know anything about BlueTooth or networking, so this is all the result of me bumbling around with little more than Google at my side. Maybe someone here knows the nuances of the SerialPort class enough to know what I'm doing wrong.
Thanks to all who can offer any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
听起来当表单关闭时
SerialPort
正在被销毁,因为表单拥有该对象。将其从表单设计器移到应用程序代码中,应该没问题。It sounds like the
SerialPort
is being destroyed when the form closes because the form owns the object. Move it out of the form designer and into the application code and you should be fine.