【问题标题】:C#, How to hande SSH timeout Exception with SharpSSHC#,如何使用 SharpSSH 处理 SSH 超时异常
【发布时间】:2013-05-02 21:43:46
【问题描述】:

我正在尝试连接到远程服务器以使用 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# 应用程序在遇到异常时再次尝试连接命令?

【问题讨论】:

  • 你能不能不把它包在一个try catch中,如果它失败了再试一次

标签: c# exception timeout sharpssh


【解决方案1】:

尝试使用 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
            }
        }

【讨论】:

  • 看起来不错。我可以试一试,没有双关语。如果 Y 发生,还有一个命令可以将程序路由到代码中的特定点 X。我不确定它叫什么,所以我什至无法查找它。有人明白我的意思吗?
  • 也许你的意思是goto 命令,但我认为你应该创建一个新的方法/函数并调用它
  • 是的,GOTO 可能也不会这样做。如果我找不到更好的方法,我可能会使用 try catch 场景。我更喜欢做的是调整 MySqlConnection 对象以在 IO 超时时自动重新连接或重试。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-19
  • 1970-01-01
  • 2023-03-18
  • 1970-01-01
  • 2020-01-29
  • 2020-12-09
相关资源
最近更新 更多