Thursday, August 1, 2013

System.IO.Ports.SerialPort Work Around

I’m adapting NiVek to communicate with my Windows 8 machine via a serial port…sorry no serial port support yet in Windows Store apps Sad smile

As I’m doing development, I’m constantly rebooting NiVek which drops and recreates the USB virtual serial port.  When it does this, the port configuration on my machine gets “messed” up and I need to do the right sequence to restart communications.  If you’re reading this far, you probably know what I mean.

Reading the “IsOpen” property on the SerialPort instance doesn’t reliable say the port went away, I’m not going to get into whether it should or shouldn’t…it doesn’t and is the cards we’ve been dealt.  So the only way to know your port is closed is attempt to send something, if it throws an exception, well, you know it’s been closed…no comment.

Here was my original code:


Once an exception is thrown, one would think you would want to close/dispose of the serial port instance, however it throws an exception.  Note: Not sure if a using statement would make a difference, however the my current architecture that really wasn’t an option.

Enter the registry:


This will let you know the ports on your machine.

What I found was that when the exception was thrown, the serial port disappeared from the Device Manager, but it still remained in the registry while my program continued to run.  This was an important clue.  Then the next time the USB virtual serial port connected, it was already in the registry but some how was invalid…again…no real clue what happened under the hood there, all I know is if my app was running and attempting to reconnect to the newly connected serial port, but since the old registry entry never went away something didn’t go right to register the serial port and make it available to my app.

Remember from my code snippet above, when the exception was thrown, calling _nivek.Dispose() generated another exception?


By sheer accident I was stepping through the code, executed _nivek.Dispose(), an exception was thrown, but I refreshed my registry and wammo…COM7 was no longer there!


Apparently prior to Dispose() blowing up, it did enough cleanup to removed the closed COM port from the registry.

So changing my code to this piece of "art” *cough* *cough*…


…removed the COM port from the registry, handled the exception and the next time I connected my virtual serial port, the connection immediately opened.

Please feel free to comment if you have a better solution, I had to hold my nose while I wrote this, but it get’s me back to the important stuff.



No comments:

Post a Comment