System.IO.Ports.SerialPort Write() 超时

发布于 2024-09-14 05:22:54 字数 549 浏览 3 评论 0原文

我正在使用 C# (.Net Framework 2.0) 编写的程序要求能够切换到“远程模式”并通过蓝牙将 ASCII 数据发送到另一个屏幕。首先我要说的是,我不是一个非常有经验的程序员,而且我对网络一无所知,但是在昨天闲逛了 SerialPort 类之后,我能够编写一个小聊天程序,该程序在两个蓝牙连接设备之间运行良好。

然而,聊天程序仅在用户点击“发送”数据的按钮时发送数据。如果两个设备没有正确连接,我只是抛出一个 TimeoutException 以及一条错误消息。我现在正在处理的程序要大得多,并且只要 COM 端口打开,就会尝试不断写入数据。

这意味着如果两个设备没有立即连接,它必须抛出一个 TimeoutException,并且它将继续抛出它,一次又一次,直到它们正确连接。这是完全不能接受的。它会使程序速度减慢到无法使用的程度,并在调试输出中散布“TimeoutException Thrown Here”错误消息。

有没有更好的解决方案来做到这一点?通过某种方式,如果我可以确认两个设备已连接,我可以让它只写出数据,而无需不断检查(并随后在检查时出现超时错误)。

The program I'm working on in C# (.Net Framework 2.0) calls for the ability to switch over to a 'remote mode' and send ascii data to another screen via Bluetooth. I'll start by saying I'm not a very experienced programmer, and I know nothing about networking, but after fooling around with the SerialPort class yesterday I was able to work up a little chat program that worked nicely between two Bluetooth-connected devices.

The chat program, however, only sent data when the user hit a button to "send" data. If the two devices weren't properly connected I just threw a TimeoutException along with an error message. The program I'm working on now is much larger, and tries to write data constantly so long as it has the COM port open.

That means if the two devices aren't immediately connected, it has to throw a TimeoutException, and it will continue to throw it, again and again until they ARE properly connected. That's totally unacceptable. It slows the program down to the point where it isn't usable, and litters the Debug output with "TimeoutException Thrown Here" error messages.

Is there a better solution for how to do this? Some way that I can get it to only write the data out if I can confirm that the two devices are connected, without constantly checking (and subsequently getting Timeout Errors while checking).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

如日中天 2024-09-21 05:22:54

不会。串行连接是无状态的。

这意味着您不知道对方是否有人。您所能做的就是发送一些内容,然后查看是否有有意义的内容返回。

最简单的例子就是老式的模拟调制解调器。要查明是否已连接,只需发送 AT 并检查是否返回 OK

所以你的解决方案是正确的,但可能没有正确实施。您应该将连接构建序列放入 BackgroundWorker 中。因此,这些尝试将在另一个线程中完成,同时您的 GUI 保持对用户的响应。

No. A serial connection is stateless.

This means you don't know if someone is on the other side. All you can do is sending something out and take a look if something meaningful is coming back.

The easiest example for this is the good old analog modem. To find out if it is connected is to send out a AT and check if an OK comes back.

So your solution is the right one, but maybe not properly implemented. You should put your connection built-up sequence into a BackgroundWorker. So these tries will be done in another thread while your GUI stays responsive to the user.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文