Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

c# - SerialPort.GetPortNames() behavior

In my C# 2008 application, I use the SerialPort.GetPortNames() function to retrieve the list of currently available ports. What I have noticed is, when ever I plug in a USB device, it's port number i s shown in the list on my Application and when I unplug it and refresh the list, the port number is no longer there.

One phase of the application involves reading/writing data from/to the device continuously. Now, my expectation is, If I unplug the device during the operation and get the current Port list using SerialPort.GetPortNames(), the Port Name will not be there and I can use that to make the decision that the device has been unplugged.

To my surprise, the Port name is still found despite having it removed

Why is the program behaving like this? The port name isn't listed when in no-communication mode. Does it have something to do with the device being removed when it's communicating?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have to be talking about SerialPort.GetPortNames(), "GetPortList" doesn't make sense. The function iterates values in the registry, written there by your USB emulator device driver. You can have a look-see with Regedit.exe, navigate to HKLMHardwareDeviceMapSerialComm. Unplug it, press F5, if the COM port is still there then SerialPort doesn't know any better than the port still being present.

There is no prescribed behavior as to how a serial port device driver should behave when the port suddenly vanishes. Serial ports are very primitive, they date back to an era where "bug" meant a moth gumming up the teletype. There is no hardware support at all for Plug and Play, removing a port with the power turned on is equivalent to unplugging the disk drive while Windows is swapping to the paging file.

Most device drivers return an error code, it generates an uncatchable exception that crashes your program. The subject of this feedback article. Apparently your device driver doesn't do that, which ought to be preferable over bombing your program. Encouraging btw, most USB emulator device drivers are utter junk.

The ultimate workaround is simple: put a little tag on the plug "don't disconnect while in use!" It's kinda of a problem with USB, most people look at it and go "hmm, what can I do with it?". And arrive at the only answer and unplug it. After a couple of kabooms, they'll learn to not do that anymore.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...