使用 COM 端口 - 每次使用后关闭,还是始终保持打开状态? [英] using a COM port - Close after each use, or leave always open?

查看:88
本文介绍了使用 COM 端口 - 每次使用后关闭,还是始终保持打开状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

直到现在我需要发送数据时才打开,然后立即关闭.我收到随机的访问端口"错误(虽然我总是在使用后关闭端口),所以我在想也许让它一直打开.

Till now I opened when I needed to send data, and closed right away. I get random "Access to Port" errors (although I always close the port after I use it), so I was thinking maybe to leave it always open.

假设每隔一两分钟我需要在某些 COM 端口发送数据,那么正确的使用方法是什么?

What is the right approach of use, assuming that every minute or two I need to send data in some COM ports?

谢谢..

推荐答案

频繁调用 SerialPort.Close() 是一个错误.让另一个应用程序从您那里窃取端口并不是很理想.但更多的问题,以及您遇到的问题,是 Close() 不等待由 SerialPort 启动的工作线程退出.该工作线程引发 DataReceived、PinChanged 和 ErrorReceived 事件.它需要一段时间"才能退出,可能在毫秒和秒之间.再次调用 Open() 将失败,直到完成.

Calling SerialPort.Close() frequently is a mistake. Having another app steal the port away from you isn't exactly very desirable. But more problematic, and the problem you are having, is that Close() doesn't wait for a worker thread that is started by SerialPort to exit. That worker thread raises the DataReceived, PinChanged and ErrorReceived events. It takes "a while" for it to exit, could be between milliseconds and seconds. Calling Open() again will fail until that's done.

这是类中的一个缺陷,但由串行端口的常见用法引起.在应用程序终止之前,应用程序通常不会关闭它们.包括从不,避免常见的死锁场景.请注意,关闭的 MSDN 文章 对此提出了警告:

It's a flaw in the class, but induced by the common usage for serial ports. Apps don't normally close them until the app terminates. Including never, avoiding a common deadlock scenario. Do note that the MSDN article for Close warns about this:

任何应用程序的最佳做法是在调用 Close 方法后等待一段时间,然后再尝试调用 Open 方法,因为端口可能不会立即关闭.

The best practice for any application is to wait for some amount of time after calling the Close method before attempting to call the Open method, as the port may not be closed instantly.

这篇关于使用 COM 端口 - 每次使用后关闭,还是始终保持打开状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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