我是否可以使用 Ping.SendAsync 来确定我是否长时间无法从某个 IP 地址获得回复?

Can I use Ping.SendAsync to determine if I haven't been able to get a reply from an IP address for a long time?

我有一个包含 IP 地址列表的列表视图的应用程序,我正在使用 Ping.SendAsync 来 ping 地址。

 private void timer1_Tick(object sender, EventArgs e)
    {
        foreach (ListViewItem lvitem in listView1.Items)
        {
            string input = lvitem.Text; ;
            string ip = input ;
            Ping pingSender = new Ping();
            pingSender.PingCompleted += new PingCompletedEventHandler(ping_PingCompleted);
            pingSender.SendAsync(ip, 1000, lvitem);
            ((IDisposable)pingSender).Dispose();
        }
    }

 private static void ping_PingCompleted(object sender, PingCompletedEventArgs e)
    {
        ListViewItem lvitem = e.UserState as ListViewItem;
        if (e.Reply.Status == IPStatus.Success)
        {
            lvitem.ImageIndex = 0; //a "check" image
        }
        else
        {
            lvitem.ImageIndex = 1; //a "X" image
        }

        GC.Collect();

    }

我现在有 2 个结果,是成功还是其他结果。超时请求在某些 IP 地址上很常见,但大多数时候它们会 return 回复,如果我很长时间没有从某个 IP 地址获得成功回复,我想显示不同的图像时间,我该怎么做?

您可以检查 IPStatus.TimedOut 是否相等:

The ICMP echo Reply was not received within the allotted time. The default time allowed for replies is 5 seconds. You can change this value using the Send or SendAsync methods that take a timeout parameter.

您当前的实现有 1 秒超时,这意味着任何超过指定时间的 PingReply 对象都应标记为超时。

旁注:

出于某种原因,您在执行异步操作时处理 Ping class,我不太确定该代码实际如何为您工作,但您应该只处理一次检索结果后,您实际上已经完成了操作。实际上,我会把它留给 GC 自己解决。

此外,调用 GC.Collect 应该很少发生。有关更多指南,请参阅 this 问题。