Using SerialPort with USB and removing USB cable while port is open

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
If I open a com port and then remove the USB cable from PC before closing the com port then there is now way I can dispose the com port after that. Not even Environment.Exit(o) works, i.e. I can not exit my program properly.
The following code describes the problem:
SerialPort port = new SerialPort("COM94");
port.Open();
int n=0;
while (n < 10)
{
  n++;
  Thread.Sleep(1000);   
}
// (Remove USB cable before the while loop has finished)

port.Close();    // <-- wont work
port.Dispose();  // <-- neither will this
Environment.Exit(0);  // < ---and not even this one will work
How can I work around this?
Btw the same scenario will appear if the USB device crash
           

View the full article
 
Back
Top