同时ping多个服务器

时间:2014-04-11 19:20:05

标签: c# ping

我有一个listview,我尝试使用以下代码添加服务器信息:

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

但问题是该程序逐个ping服务器并且需要花费大量时间才能完成(我有80个ip用于ping并且将来可能会有更多) 那么有没有办法在同一时间ping所有的ips?

1 个答案:

答案 0 :(得分:5)

根据Ping类,您可以使用异步事件:

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...

}

编辑:添加了代码以显示添加仲裁数据/对象的可能性。