Question

I am trying to connect to a remote server to using Sharp SSH. The timeout exception I receive is a network based exception. I want the program to be more robust even if the network has problems, or if the server simply isn't available. The time out occurs at my open command and throws an IO timeout exception.

I am hoping to solve this intermittent problem from my end.

mySqlConnectionString = String.Format(
    "server={0};user={1};database=MTA;port=3306;password={2}", 
    SqlHost, mySqlUser, mySqlPass);

se = new SshExec(Host, User, Pass);
msc = new MySqlConnection(mySqlConnectionString);

// Connect to server and get the list of 
// firmware versions and serial numbers available
se.Connect();

lblConnected.Text = (se.Connected) ? "Connected" : "Not Connected";

msc.Open();         //exception happens here

My question: Is there some way I can tell the C# application to just try the connect command again should it encounter an exception?

Was it helpful?

Solution

Try using a try catch block:

        mySqlConnectionString = String.Format("server={0};user={1};database=MTA;port=3306;password={2}", SqlHost, mySqlUser, mySqlPass);

        se = new SshExec(Host, User, Pass);
        msc = new MySqlConnection(mySqlConnectionString);
        // Connect to server and get the list of firmware versions and serial numbers available
        se.Connect();

        lblConnected.Text = (se.Connected) ? "Connected" : "Not Connected";

        try
        {
            msc.Open();  //exception happens here
        }
        catch (Exception)
        {
            //do stuff, i.e. retry connection
            msc.Open();
        }

to be sure you can use a nested try/catch:

        mySqlConnectionString = String.Format("server={0};user={1};database=MTA;port=3306;password={2}", SqlHost, mySqlUser, mySqlPass);

        se = new SshExec(Host, User, Pass);
        msc = new MySqlConnection(mySqlConnectionString);
        // Connect to server and get the list of firmware versions and serial numbers available
        se.Connect();

        lblConnected.Text = (se.Connected) ? "Connected" : "Not Connected";

        try
        {
            msc.Open();  //exception happens here
        }
        catch (Exception)
        {
            //do stuff, i.e. retry connection
            try
            {
                msc.Open();  //exception happens here
            }
            catch (Exception)
            {
                //do stuff
            }
        }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top