C# 服务器性能:如何退出 foreach 循环


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循环。结果不断重复。

您发布的代码没有任何问题。 一旦你删除了所有不必要的或与例程的核心无关的代码,你就剩下:

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();

而且该代码工作正常。

在您关于同一主题的另一个问题中,您似乎正在使用计时器启动它。这将导致代码一遍又一遍地执行。

if (some_success_validation) 
{
  break;
}

最新更新