类似于此处的其他ping问题,我们需要同时ping许多IP地址。我们认为从这里获得许多回应和示例之后,它运行得很好,但是由于尝试同时或什至彼此接近ping超时,我们遇到了ping失败的情况。
我们在另一个ping监视程序上测试了IP列表,并且不会发生超时。该问题是特定于我们的应用程序的。
在我们的应用程序中,每个“设备”都有一个RouterProperties类,其中包含其名称,IP地址等。我们从这些设备的可观察集合中ping,从其RouterProperty中获取其IP地址。
//OUR MAIN PING SCHEDULER
private async void PingAllDevices(object sender, EventArgs e)
{
var allPingTasks = new List<Task>();
int numOfDevices = 1;
//Assign a task to each device.
foreach (RouterProperties device in devices)
{
await Task.Delay(10);
Console.WriteLine("Pinging device #" + numOfDevices + " : " + device.RouterIP);
numOfDevices++;
allPingTasks.Add(AsyncPingDevice(device));
}
//Block here for all created tasks.
await Task.WhenAll(allPingTasks);
}
}
//OUR PING TASK
async Task AsyncPingDevice(RouterProperties device)
{
// Get device IP address to ping.
string deviceIP = device.RouterIP;
try
{
Ping pingSender = new Ping();
PingOptions options = new PingOptions();
var reply = await pingSender.SendPingAsync(deviceIP, (int.Parse(Properties.Settings.Default.PingTimeout)), buffer, pingOptions);
Console.WriteLine(deviceIP + " has responded.");
if (reply.Status == IPStatus.Success)
{
device.PingCounter = 0;
}
else
{
if (device.PingCounter <= 3)
{
device.PingCounter++;
}
}
}
catch
{
if (device.PingCounter <= 3)
{
device.PingCounter++;
}
}
await Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action( () =>
{
if (device.IsDeactivated != true)
{
switch (device.PingCounter)
{
case 0:
device.Color = "#FF8AA587";
break;
case 1:
device.Color = "#FF9AB999";
break;
case 2:
device.Color = "#FFFCCEAA";
break;
case 3:
device.Color = "#FFF4837D";
break;
case 4:
device.Color = "#FFEB4960";
break;
}
}
}));
}
在运行代码时,无论是否在ping调度程序中使用task.delay来分隔ping,我们最终都会从被ping的设备获得不一致的结果。