How to ignore an exception AND complete the try

前端 未结 3 651
抹茶落季
抹茶落季 2021-01-27 06:57

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,

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-27 07:22

    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);
    }
    

提交回复
热议问题