我想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;
}
请帮帮我。
谢谢
答案 0 :(得分:0)
或使用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)
{
}
});
}
}