我正在使用下面的代码来启动异步ping负载。我还有一个PingCompletedEventHandler调用的函数,此函数将成功ping的地址添加到列表中,以供以后使用。

我想知道所有ping线程完成后如何调用函数?

    public static void PingRange(IPRange range)
    {

        foreach (IPAddress ip in range.GetAllIP())
        {
            // Create Pinger
            AutoResetEvent waiter = new AutoResetEvent(false);
            Ping pingSender = new Ping();
            pingSender.PingCompleted += new PingCompletedEventHandler(pingSender_PingCompleted);

            // Create a 32 byte data buffer
            string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
            byte[] buffer = Encoding.ASCII.GetBytes(data);

            // Wait 4 seconds for a reply
            int timeout = 4000;

            PingOptions options = new PingOptions(64, true);

            pingSender.SendAsync(ip, timeout, buffer, options, waiter);
            PingStartCount++;
        }
    }

最佳答案

如果您使用的是.NET 4.0,则这相当容易。您可以使用CountdownEvent类而不是PingStartCount计数器和waiter事件。 CountdownEvent将同时执行这两项工作。

public static void PingRange(IPRange range)
{
    var finished = new CountdownEvent(1);
    foreach (IPAddress ip in range.GetAllIP())
    {
        finished.AddCount(); // Indicate that a new ping is pending
        var pingSender = new Ping();
        pingSender.PingCompleted +=
          (sender, e) =>
          {
            finished.Signal(); // Indicate that this ping is complete
          };
        string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        byte[] buffer = Encoding.ASCII.GetBytes(data);
        PingOptions options = new PingOptions(64, true);
        pingSender.SendAsync(ip, 4000, buffer, options, waiter);
    }
    finished.Signal(); // Indicate that all pings have been submitted
    finished.Wait(); // Wait for all pings to complete
}

08-07 13:10