如何在 C# 中异步监听多个串口
我有一个应用程序可以监听 USB 转串口转换器上的硬件。我的应用程序应该同时监视多个串行端口。
我循环需要监听的串行端口,并为每个端口创建一个线程。在线程中我有我的数据处理例程。
当我分配一个端口时,它运行完美。当我听另一首时,它也有效。然而,当我打开两个端口时,第二个端口在调用 serialPort.Open()
时总是抛出 UnauthorizedAccessException
。无论我以什么顺序打开端口,第二个端口总是失败。
我在 while 循环中使用 serialPort.ReadLine()
监听端口。
.NET 可以同时打开多个端口吗?我可以两者都听吗?或者我应该使用另一种(线程安全?)方式来访问我的串行端口事件?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该异常具有非常特定的含义,它告诉您有人已经打开了该端口。那会是谁?当您打开第二个端口时,请仔细检查四次,确保您确实使用了不同的端口名称。
下一步是将 USB 仿真器带到停车场,用你的车在它上面碾压几次,这样它就不会再让程序员发疯了。从使用不同设备驱动程序供应商的另一家制造商处获取一个。
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.