4
votes

I have an application that listens to a piece of hardware on a USB to Serial converter. My application should monitor more than one serial port at the same time.

I loop the serial ports I need to listen to, and create a thread for each port. In the thread I have my data handing routine.

When I assign one port, it runs flawlessly. When I listen to the other one, it also works. When I open both ports however, the second port always throws an UnauthorizedAccessException when calling serialPort.Open(). It does not matter in what order I open the ports, the second one always fails.

I listen to the ports using serialPort.ReadLine() in a while loop.

Can .NET open more than one port at the same time? Can I listen to both? Or should I use another (thread safe?) way to access my serial port events?

1
I am old and have probably being writing code for serial ports before you were born. So don't take this wrong, this "serialPort.ReadLine() in a while loop." tells me that you haven't fully grasped the datareceived event handler. When I started coding again it was with MS Visual Basic, and one of the first pieces of software I wrote was a serialport handler. If you want to look at it let me know, it is on another forum. I wish I had time to re-write it, but I believe it will work with more than one serial port. I tested it at speeds of up to 900Kbps.dbasnett
You are right, I am not using the event and am aware of that :-) I will, as soon as I get a chance to refactor this code :-)Kamiel Wanrooij

1 Answers

4
votes

The exception has a very specific meaning, it tells you that somebody already has the port opened. Who could that be? Triple-check four times that you are really using a different port name when you open the 2nd one.

Next step is to take the USB emulator to the parking lot and run over it with your car several times so it can no longer drive a programmer nuts. Get one from another manufacturer that uses a different device driver supplier.