我正在尝试连接到远程服务器以使用夏普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块:
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
}
}