使用 COM 端口 - 每次使用后关闭,还是始终打开?

using a COM port - Close after each use, or leave always open?(使用 COM 端口 - 每次使用后关闭,还是始终打开?)

本文介绍了使用 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.

这是类中的一个缺陷,但由串行端口的常见用法引起.在应用程序终止之前,应用程序通常不会关闭它们.包括从不,避免常见的死锁情况.请注意,关于 Close 的 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 端口 - 每次使用后关闭,还是始终打开?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:使用 COM 端口 - 每次使用后关闭,还是始终打开?

基础教程推荐