I have following Code-1 for pinging to single IP and get the ping results. It is working as expected. Now I want to ping to multiple IP's (just few, not hundred of IP's) at the same time, and get their results.
I have written Code-2 but I don't know how to get the results like roundtrip time and ping status for each ping process. In Code1 I got these from the var reply. But in Code2 I don't know how to fetch them?
Code1*****
private async ValueTask PingMachine(string ipadress, string iptype)
{
var timesToPing = 4;
var counter = 1;
while (counter <= timesToPing)
{
var reply = await Pinger(ipadress);
TagService.log_Win.AppendLine($"Pinged {ipadress} {counter} times time:{reply.RoundtripTime} status: {reply.Status.ToString()}");
}
counter ;
}
}
private async ValueTask<PingReply>
Pinger(string ipAddress)
{
var ping = new Ping();
var reply = await ping.SendPingAsync(ipAddress);
return reply;
}
Code2*****
public static string[] addresses = { "10.92.114.73", "10.92.114.74", "10.92.114.75" };
private async Task<List<PingReply>> Pinger2()
{
var tasks = addresses.Select(ip => new Ping().SendPingAsync(ip, 2000));
var reply = await Task.WhenAll(tasks);
return reply.ToList();
}
Update2******
var replies = await Pinger2();
foreach (var r in replies)
{
TagService.log_Win.AppendLine(replies.Select(r => r.RoundtripTime).ToString());
}
private async Task<IEnumerable<PingReply>> Pinger2()
{
var tasks = addresses.Select(async ip => await new Ping().SendPingAsync(ip, 2000));
var replies = await Task.WhenAll(tasks);
return replies;
}
CodePudding user response:
You just need to await
within the lambda
private async Task<IEnumerable<PingReply>> Pinger2()
{
var tasks = addresses.Select(async ip => await new Ping().SendPingAsync(ip, 2000));
var replies = await Task.WhenAll(tasks);
return replies;
}