views:

37

answers:

1

I have an application which calls SerialPort.Open() ... This works fine and data is read/written through the port. However if a user decides to kill the Application through the TaskManager the application will close without calling my destructor calling SerialPort.Close().

This in turn (only sometimes) causes the following error:

Access to the port 'COM2' is denied.

This occurs on re-startup of the application. I've read enough posts to know that this wouldn't happen if .Close() was properly called. So far I have handled this by having a timer which reattempts the .Open().. which eventually succeeds (that is I think it does most of the time).

My question is this:

Is there a DLLImport method which will allow me to free the Comm port resource?

+2  A: 

I rubbed my crystal ball and it revealed that you are using a USB driver that emulates a serial port, that the user decided it was a good idea to kill the process because she jerked the USB connector out of the socket and that she is running a pre-Vista version of Windows.

Roughly any two combinations out of that list. Yes, doesn't work, you cannot kill a process when it has a kernel thread going that is completing an I/O request that cannot finish. You can tell from TaskMgr.exe when you use View + Select Columns and tick Handles. The process will zombie with one handle opened. Won't close until the driver actually lets go. Won't happen, USB drivers suck like that.

Starting the program again will bomb, the first instance of the process still has the port opened. Access denied.

Tell the user to keep her hands off the connector. Or buy another one from a different manufacturer. You can help by adding a "Safely Remove Hardware" menu option to your program. That calls the SerialPort.Close() method. Call Sleep(2500) and display a message box that it is okay to unplug it.

Hans Passant
In my experience this combination (unplug serial-USB adapter, then try to kill process) is a good way to summon a BSOD on certain USB-serial converter drivers from certain manufacturers. These buggy drivers even pass WHQL. Start by making sure the very latest drivers are installed.
Ben Voigt
No, this is a serial port off of an Intel board on Windows XP.
maxfridbe