if (Properties.Settings.Default.ICMP_SERVER_LIST.ToString() != string.Empty)
{
string ServersToPing = Properties.Settings.Default.ICMP_SERVER_LIST;
string[] ServerArrays = ServersToPing.Split(new Char[] { ' ' },
StringSplitOptions.RemoveEmptyEntries);
foreach (string server in ServerArrays)
{
string host = server.Substring(0, server.IndexOf(':'));
int port = Convert.ToInt32(server.Substring(server.LastIndexOf(":") + 1).ToString());
string[] serverInfo = ServersToPing.Split(new Char[] { ' ' },
StringSplitOptions.RemoveEmptyEntries);
string res = PingServerViaICMP(server, RespTimeOut);
Ping pingreq = new Ping();
PingReply pingrep = pingreq.Send(host, 30 * 1000);
res = string.Format("{0}:time={1}ms", pingrep.Address.ToString(),
pingrep.RoundtripTime.ToString());
txtLog.Text += host + ": " + res + " " + Environment.NewLine;
}
Array.Clear(ServerArrays, ServerArrays.GetLowerBound(0), ServerArrays.GetLowerBound(0));
ServersToPing = "";
}
app.config文件中有7个服务器名称和端口。我试图命中服务器以获得时间。我得到了预期的结果,但我无法摆脱foreach循环。结果不断重复。
答案 0 :(得分:1)
if (some_success_validation)
{
break;
}
答案 1 :(得分:1)
您发布的代码没有任何问题。一旦你删除了所有不必要的代码或与例程的核心无关的代码,你就会离开:
string ServersToPing = "localhost:80 localhost:443";
string[] ServerArrays = ServersToPing.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string server in ServerArrays)
{
string host = server.Substring(0, server.IndexOf(':'));
Ping pingreq = new Ping();
PingReply pingrep = pingreq.Send(host, 30 * 1000);
Console.WriteLine("{0}:time={1}ms", pingrep.Address.ToString(), pingrep.RoundtripTime.ToString());
}
Console.ReadLine();
该代码工作得很好。
在关于相同主题的other question中,您似乎正在使用计时器启动此功能。这将导致代码一次又一次地执行。