【发布时间】:2021-11-03 09:32:30
【问题描述】:
我有一些代码想用于网络上的设备发现。 它只是简单地 ping 所述网络上的任何 IP 地址,如果得到答案,则将地址添加到列表中。
代码如下:
static void Main(string[] args){
//do stuff to get subnetmask and local address
//succession of for loop to increment ip address
{
PingAsync(ip_address);
}
//here I display the list of addresses that answered the ping
//first Readline() is to manually wait for threads to end so the list isn't empty
Console.Readline()
Console.WriteLine("List of all devices found :\n");
ipList.ForEach(delegate (string str)
{
Console.WriteLine($"\t=> {str}");
});
Console.ReadLine();
}
private static void PingAsync(IPAddress address)
{
AutoResetEvent waiter = new AutoResetEvent(false);
Ping pingSender = new Ping();
//items are added to ipList in PingCompletedCallback()
pingSender.PingCompleted += new PingCompletedEventHandler(PingCompletedCallback);
string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte[] buffer = Encoding.ASCII.GetBytes(data);
int timeout = 1200;
PingOptions options = new PingOptions(64, true);
pingSender.SendAsync(address, timeout, buffer, options, waiter);
}
在 PingCompletedCallback 方法中,我将项目添加到将显示在主列表中的列表
private static void PingCompletedCallback(object sender, PingCompletedEventArgs e)
{
Program prog = new Program();
if (e.Cancelled)
{
Console.WriteLine("Ping failed !");
Console.WriteLine(e.Error.ToString());
((AutoResetEvent)e.UserState).Set();
}
if(e.Error != null)
{
Console.WriteLine("Ping failed !");
Console.WriteLine(e.Error.ToString());
((AutoResetEvent)e.UserState).Set();
}
PingReply reply = e.Reply;
if(reply.Status.ToString().Equals("Success", StringComparison.OrdinalIgnoreCase))
{
//If the ping succeeds add the address to a list
ipList.Add(reply.Address.ToString());
}
((AutoResetEvent)e.UserState).Set();
}
代码在发现设备方面运行良好,唯一的问题是地址列表。如果我不手动等待所有线程结束,它将显示为空。
根据这些帖子(1)(2) 和其他一些帖子,使用 Thread.join 或 Task.Waitall 是要走的路。但是,与他们不同的是,我不是自己创建线程,而是让 SendAsync() 创建自己的线程。
另外,我无法更改 PingAsync() 以使其等待 SendAsync(),因为它返回 void。
我想知道你会在打印/使用 ipList 之前等待线程结束。
【问题讨论】:
-
这里有很多问题。但是,您最好使用更现代的
SendPingAsync然后等待它。
标签: c# multithreading