C#Ping.Send导致GUI冻结

时间:2015-07-18 02:19:41

标签: c# user-interface ping freeze

第一次使用Stackoverflow,所以我会尽力做到最好。

我正在制作一个小应用来ping一些服务器,我遇到的问题是程序的GUI在等待响应时锁定。 这就是我到目前为止,Button_Click是“Ping IP”按钮,ping_box是一个包含响应时间的文本框,ip_address是一个字符串形式的IP地址。

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        Stopwatch s = new Stopwatch();
        s.Start();

        while (s.Elapsed < TimeSpan.FromSeconds(2))
        {
            using (Ping p = new Ping())
            {
                ping_box.Text = (p.Send(ip_address, 1000).RoundtripTime.ToString() + "ms\n");

                if (ping_box.Text == "0ms\n")
                {
                    ping_box.Text = "Server is offline or exceeds 1000ms.";
                }
            }
        }
        s.Stop();
    }

因此,在当前状态下,它会重复ping IP地址两秒钟,并将响应时间放入文本框,在此期间GUI会锁定。 我需要记录这个,因为我希望文本框的响应时间随每次ping更新(如果响应时间是500毫秒,那么文本框应该更新四次)。

我尝试过使用Ping.SendAsync但无法让它工作,任何指针或帮助都会非常感激:)

2 个答案:

答案 0 :(得分:2)

我认为这应该有帮助...... 您可以根据需要进一步修改

private void button1_Click(object sender, EventArgs e)
{
    AutoResetEvent waiter = new AutoResetEvent(false);
    IPAddress ip = IPAddress.Parse("192.168.1.2");
    var pingSender = new Ping();

    pingSender.PingCompleted += PingCompletedCallback;
    pingSender.SendAsync(ip, 1000, waiter);
}

private void PingCompletedCallback(object sender, PingCompletedEventArgs e)
{
    // If an error occurred, display the exception to the user. 
    if (e.Error != null)
    {
        MessageBox.Show(string.Format("Ping failed: {0}", e.Error.ToString()), 
                        "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

        // Let the main thread resume. 
        ((AutoResetEvent)e.UserState).Set();
    }

    DisplayReply(e.Reply);

    // Let the main thread resume.
    ((AutoResetEvent)e.UserState).Set();
}

public void DisplayReply(PingReply reply)
{
    if (reply == null)
        return;

    ping_box.Text = string.Format("Ping status: {0}, RoundTrip time: {1}", 
                                    reply.Status,
                                    reply.RoundtripTime.ToString());

}

答案 1 :(得分:1)

  


  允许应用程序确定远程计算机是否正常   可通过网络访问。

当您调用Ping时,您的主线程(即您的UI线程)已停止并等待ping响应,这就是您的应用程序冻结的原因。

溶液: 您需要将Ping放在另一个线程