异步获取IP Ping结果c#

Get IP Ping results Asynchronously c#

我有一个 IP 地址列表。我想同时启动一个 ping 进程,并且应该是异步的。

private async Task<List<PingReply>> PingAsync()
{
   Ping pingSender = new Ping();
  var tasks = theListOfIPs.Select(ip => pingSender.SendPingAsyn(ip,2000));
   var results = await Task.WhenAll(tasks);

   return results.ToList();
}

据我了解,此操作将等待所有 ping 结果返回。我想做的是,每当完成单个结果时,我都想利用该结果。所以,一旦一个 ping returns 结果,我想立即存储它,而不等待其他 ping 完成。

我该怎么做?

在这种情况下你可以使用 WaitAny

  var results = await Task.WaitAny (tasks);

以下版本是登录器,但我认为这可能对您有所帮助..

bool onetaskCompleted= false;
private readonly Object obj = new Object();

private async Task<List<PingReply>> PingAsync()
{
   Ping pingSender = new Ping();
   var tasks = theListOfIPs.Select(ip => pingSender.SendPingAsyn(ip,2000));
   List<Task> continuetask = new List<Task>();
   foreach(Task t in taks)
   {
     continuetask.Add(t.ContinueWith(Action));
   }

   var results = await Task.WhenAll(continuetask);

   return results.ToList();
}

private void ContinuationAction()
{
     lock(obj)
     {
       if(!onetaskCompleted) 
          onetaskCompleted = true;
     }
     if(!onetaskCompleted)
     {
       //execute code 
     }
}

What i want to do is whenever a single result is completed i want to utilize that result.

我认为最干净的解决方案是定义一个 "ping and process" 操作:

private async Task<PingReply> PingAndProcessAsync(Ping pingSender, string ip)
{
  var result = await pingSender.SendPingAsync(ip, 2000);
  ProcessPingResult(result);
  return result;
}

然后 运行 多个并发:

private async Task<List<PingReply>> PingAsync()
{
  Ping pingSender = new Ping();
  var tasks = theListOfIPs.Select(ip => PingAndProcessAsync(pingSender, ip));
  var results = await Task.WhenAll(tasks);
  return results.ToList();
}