Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using a COM port - Close after each use, or leave always open?

Tags:

c#

serial-port

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.

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

Thanks..

like image 574
Itay Avatar asked May 27 '13 16:05

Itay


People also ask

What do you use COM ports for?

A COM port is simply an I/O interface that enables the connection of a serial device to a computer. You may also hear COM ports referred to as serial ports. Most modern computers are not equipped with COM ports, but there are many serial port devices still in use that use the interface.

How do I know if a COM port is working?

To test if the computer COM port is functioning correctly, you can do a simple loopback test. (In a loopback test, a signal is sent from a device and returned, or looped back, to the device.) For this test, connect a serial cable to the COM port that you want to test. Then short pin 2 and pin 3 of the cable together.

What is meant by COM port?

COM (communication port) is the original, yet still common, name of the serial port interface on PC-compatible computers. It can refer not only to physical ports, but also to emulated ports, such as ports created by Bluetooth or USB adapters.


1 Answers

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.

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:

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.

like image 122
Hans Passant Avatar answered Sep 30 '22 17:09

Hans Passant