Reopening and closing the port is not recommended. See the "Notes" section in the "MSDN Library" article for SerialPort.Close (). There the background thread, which needs to be turned off before the port opens again, takes time. The amount of time is not predictable.
The Close () method can easily slow down if the DataReceived event handler is currently running. The most common way to get a deadlock is to call Control.Invoke () in the event handler. Make sure that you are not using any code in the event handler that blocks or requires switching the context of the stream. Using BeginInvoke () is fine.
The inability to kill the program is caused by a problem in the serial port device driver. Launch Taskmgr.exe, the Process tab, View + Select Columns and check "Handles". If, after killing the program, you see the βHandlesβ column showing 1, then the serial port driver hangs on an I / O request that it does not execute. A process cannot end until all of its kernel-mode threads have completed.
There is little that can be done on this particular problem, except to hope for a driver update or switching to another provider. Especially USB serial port emulators are known for having lousy device drivers. You get rid of the troublemaker, for example, taking it out in the parking lot and launching it several times using your car.
Another typical problem with USB emulators is that they are so easy to disconnect while they are in use. This works the same way as popping a flash drive from a socket while Windows is running. It would also be a good way to make a device driver damage .NET versions up to version 4.0, suffer a heart attack in the background thread when the device suddenly disappears. Briefly from the update, a small sign next to the connector that says: "Do not disconnect during use!" is a practical solution. They will still miss him a couple of times.
Fwiw, otherwise it means that the "Safely Remove Hardware" icon exists. You will get a solid "Don't do this!" if your program uses a port. But, of course, the operating system is powerless to force users to actually use it. Apple patented a method to make it fault tolerant by detecting the user's fingers on the device :)
Hans passant
source share