1

I have an application which contains a listview that has a list of IP address, i'm using Ping.SendAsync to ping the addresses.

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

    }

I have 2 results right now, if it's a success or if it's something else. Timed out requests are common on some of the IP address but they'll return a reply most of the time, I want to display a different image if I haven't gotten a success reply from an ip address for a long time, how can I do this?

sabre
  • 207
  • 6
  • 18

1 Answers1

1

You can check for equality with 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.

Your current implementation has a 1 second timeout, which means that any PingReply object which passes that specified time should be flagged as timed out.

Side Note:

For some reason you're disposing the Ping class while the asynchronous operation is executing, i'm not really sure how that code actually works for you, but you should only dispose once you're actually done with the operation after the results are retrieved. Actually, i'd leave it up to the GC to figure that out on its own.

Also, calling GC.Collect should happen pretty rarely. See this question for more guidelines.

Community
  • 1
  • 1
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321