C# Ping.Send 导致 GUI 卡住

标签 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 但无法正常工作,非常感谢任何指示或帮助:)

最佳答案

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

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

}

关于C# Ping.Send 导致 GUI 卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31487132/

相关文章:

c# - 找不到类型或命名空间名称 'Ping',尽管存在依赖关系和使用

iphone - iOS/iPhone 如何 ping 服务器 ip 地址?

c# - 如何访问动态按钮的事件处理程序? Visual Studio 2015 WPF

java - MVC 和 Java GUI 监听器

Java GUI 更好地删除或 setVisible(false)?

.net - 如何在 WPF 应用程序中实现气球消息

c# - Ping.SendAsync() 始终成功,即使客户端在 cmd 中不可 ping

c# - 为 serilog sink 指定更高的日志级别

c# - 模拟 AppDomain 回收

c# - 使用数据集 [asp.net, c#] 在 SQL Server 中添加新行