从下面的代码中,有时候,它不会回复所有的ping请求,并且会等待无限的时间。是否有任何死锁问题?如果是的话如何处理?如何在没有任何死锁的情况下为每个ip获得正确的结果?
class Program
{
static Semaphore PingSender { get; set; }
static object lockObj = new object();
static void Main(string[] args)
{
long pingSent = 0;
long pingReceived = 0;
PingSender = new Semaphore(10000, 10000);
for (int dotNoDot = 1; dotNoDot <= 255; dotNoDot++)
{
for (int dotNo = 1; dotNo <= 255; dotNo++)
{
try
{
string ipAddress = string.Format("111.222.{0}.{1}", dotNoDot, dotNo); //Please change necessary ip base
PingSender.WaitOne();
Ping ping = new Ping();
ping.PingCompleted += (sender, eventArgs) =>
{
//lock (lockObj)
//{
PingSender.Release(1);
Console.WriteLine(string.Format("{0}) Address: {1} and Status: {2}", pingReceived, eventArgs.UserState, eventArgs.Reply.Status));
if (eventArgs.Reply.Status == IPStatus.Success)
{
//collect online machines
}
Interlocked.Increment(ref pingReceived);
if (pingReceived == pingSent)
{
//done
}
//}
};
//lock (lockObj)
//{
pingSent++;
// }
ping.SendAsync(ipAddress, 10000, ipAddress);
}
catch (Exception ex)
{
}
}
}
}
}