1

我正在尝试连接到远程服务器以使用 Sharp SSH。我收到的超时异常是基于网络的异常。即使网络有问题,或者服务器根本不可用,我也希望程序更加健壮。超时发生在我的打开命令并引发 IO 超时异常。

我希望从我的角度解决这个间歇性问题。

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

我的问题:有什么方法可以告诉 C# 应用程序在遇到异常时再次尝试连接命令?

4

1 回答 1

2

尝试使用 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
            msc.Open();
        }

确保您可以使用嵌套的 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
            }
        }
于 2013-05-08T16:23:22.087 回答