multithreaded ping IPs

本文关键字:IPs ping multithreaded | 更新日期: 2023-09-27 17:53:51

我想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;
    }

请帮帮我。

谢谢

multithreaded ping IPs

或者使用Task.Factory的版本。StartNew,不等待完成,如果1个IP完成,然后将其添加到listView,快速和肮脏,只是为了示例:

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