Skan So
Skan So

Reputation: 153

Pinging several servers in the same time

I have a listview and i try to add server information with this code:

foreach(string element in ids)
{
   int id = Int32.Parse(element);
   ListViewItem item = new ListViewItem(name[id]);
   item.SubItems.Add(ip[id]);
   Ping pingsv = new Ping();
   PingReply pingreply = pingsv.Send(ips[id],500);
   if (pingreply.RoundtripTime == 0)
       item.SubItems.Add("500+");
   else
       item.SubItems.Add(pingreply.RoundtripTime.ToString());
}

But the problem is that the program ping the servers one by one and it takes a lot of time to complete(i have like 80 ip's to ping and there might be more in the future) So is there any way to ping all the ips in the same time?

Upvotes: 0

Views: 247

Answers (1)

Khôi
Khôi

Reputation: 2143

According to the Ping class you may use an asynchronous event:

foreach(string element in ids)
{
   int id = Int32.Parse(element);
   ListViewItem item = new ListViewItem(name[id]);
   item.SubItems.Add(ip[id]);
   Ping pingsv = new Ping();
   pingsv.PingCompleted += pingsv_PingCompleted;

   pingsv.SendAsync(IPAddress, 500, id);

}

[... somewhere else in the same class ...]

void pingsv_PingCompleted(object sender, PingCompletedEventArgs e)
{
      long pingtime = e.Reply.RoundtripTime;
      // do something with pingtime...

      // id has been saved to UserState (see above)
      string id = (string)e.UserState;

      // do something with id...

}

EDIT: Added code to show the possiblity to add arbitary data / objects.

Upvotes: 5

Related Questions