So I\'ve been battling this issue for about a week now and think I know the issue but I don\'t want to report an answer there until I have it pegged down.
In a nutshell,
From SerialPort.Open:
Only one open connection can exist per SerialPort object. The best practice for any application is to wait for some amount of time after calling the Close method before attempting to call the Open method, as the port may not be closed instantly.
And
The port is in an invalid state.
- or -
An attempt to set the state of the underlying port failed. For example, the parameters passed from this SerialPort object were invalid.
I bet this is what is happening... your SerialPort was recently open and now you're trying to open it again before it's ready.
My advice is to write a loop, and sleep a bit between Opening attempts. Figure out how many times you're willing to try over how long of a period. break
out of the loop when you succeed.
foreach(int i in Enumerable.Range(1, numberOfAttempts)
{
try
{
serialPort1.Open();
break;
}
catch(Exception ex)
{
//log attempt #i failed because of ex
}
Thread.Sleep(millisecondsToWait);
}
In general, if you have a line of code causing an exception, and there's additional work to be done whether or not the exception occurred, you should just use a catch
, and put the stuff you want done anyway outside (after) the try
/catch
.
For your particular case (described in your other question), you are dealing with the horrible brokenness that is .NET System.IO.Ports.SerialPort
. Opening the serial port succeeded, but SerialPort.Open
is a complicated method that does a bunch of extra stuff, and insists on closing the port if any of that extra (and unnecessary) stuff fails. I've found other problems with System.IO.Ports.SerialPort
as well (e.g. inability to open ports by their internal device name). IMO, the sooner you get rid of System.IO.Ports.SerialPort
the better.
You can either p/invoke the Win32 Serial Port functions (CreateFile
and the rest are here) or find someone who already wrote a wrapper library (I did, but it isn't available publically).
serialPort1.Open();
is what is throwing the exception. Normally when you code, if an exception happens you do clean up of the connections.
As others mentioned, if you keep calling this same method, you'll keep getting exception unless things about the call change.
So understanding that, my suggestion would be that you look for other ways to open the serial port, other than the serialPort1.Open(); call. There may or may not be built in ways in C#. So you might have to be creative :)