多线程 ping IP

multithreaded ping IPs

我想 ping 一个 IP 列表,但它不起作用。

我已经在控制台应用程序中使用了这个功能并且它正在运行。

string[] addresses = { "192.168.1.2", "192.168.1.3", "192.168.1.4" };
    void show()
    {
        List<Task<PingReply>> pingTasks = new List<Task<PingReply>>();
        foreach (var address in addresses)
        {
            pingTasks.Add(PingAsync(address));
        }

        Task.WaitAll(pingTasks.ToArray());
        int i = 0;
        listView1.Clear();
        listView1.Columns.Add("Device IP", 100);
        listView1.Columns.Add("ping", 60);
        foreach (var pingTask in pingTasks)
        {
            string[] A = { addresses[i], pingTask.Result.RoundtripTime.ToString() };
            ListViewItem item = new ListViewItem(A);
            listView1.Items.Add(item);
            i++;
        }
    }

    Task<PingReply> PingAsync(string address)
    {
        var tcs = new TaskCompletionSource<PingReply>();
        Ping ping = new Ping();
        ping.PingCompleted += (obj, sender) =>
        {
            tcs.SetResult(sender.Reply);
        };
        ping.SendAsync(address, new object());
        return tcs.Task;
    }

请帮助我。

谢谢

或使用Task.Factory.StartNew的版本,不等待完成,如果1个IP完成则将其添加到listView,Quick and Dirty,仅供示例:

private void RunPing2()
{
  listView1.Clear();
  listView1.Columns.Add("Device IP", 100);
  listView1.Columns.Add("ping", 60);

  string[] addresses = {"192.168.1.6", "192.168.1.3", "192.168.1.4", "google.com"};
  var syncObj = new object();
  foreach (var address in addresses)
  {
    Task.Factory.StartNew(() =>
    {
      var ping = new Ping();
      try
      {
        var reply = ping.Send(address);
        lock (syncObj)
        {
          Invoke(new MethodInvoker(delegate
          {
            string[] A = {address, reply.RoundtripTime.ToString()};
            var item = new ListViewItem(A);
            listView1.Items.Add(item);
          }));
        }
      }
      catch (Exception)
      {
      }
    });
  }
}