How to Perform Multiple “Pings” in Parallel using C#

前端 未结 6 1424
粉色の甜心
粉色の甜心 2020-12-08 11:48

I am trying to calculate the average round-trip time for a collection of servers. In order to speed things up, I would like to perform the pings in parallel. I have writte

6条回答
  •  天命终不由人
    2020-12-08 12:24

    A solution:

    internal class Utils
    {
        internal static PingReply Ping (IPAddress address, int timeout = 1000, int ttl = 64)
        {
                PingReply tpr = null;
                var p = new Ping ();
                try {
    
                    tpr = p.Send (address,
                        timeout,
                        Encoding.ASCII.GetBytes ("oooooooooooooooooooooooooooooooo"),
                        new PingOptions (ttl, true));
    
                } catch (Exception ex) {
    
                    tpr = null;
    
                } finally {
                    if (p != null)
                        p.Dispose ();
    
                    p = null;
                }
    
                return tpr;
            }
    
            internal static List PingAddresses (List addresses, int timeout = 1000, int ttl = 64)
            {
                var ret = addresses
                    .Select (p => Ping (p, timeout, ttl))
                    .Where (p => p != null)
                    .Where (p => p.Status == IPStatus.Success)
                    .Select (p => p).ToList ();
    
                return ret;
            }
    
            internal static Task PingAddressesAsync (List addresses, Action>> endOfPing, int timeout = 1000, int ttl = 64)
            {
    
                return Task.Factory.StartNew> (() => Utils.PingAddresses (
                    addresses, timeout, ttl)).ContinueWith (t => endOfPing (t));
    
            }   
    }
    

    And using:

    Console.WriteLine ("start");
    
    Utils.PingAddressesAsync (new List () { 
                        IPAddress.Parse ("192.168.1.1"), 
                        IPAddress.Parse ("192.168.1.13"), 
                        IPAddress.Parse ("192.168.1.49"),
                        IPAddress.Parse ("192.168.1.200")
                    }, delegate(Task> tpr) {
    
                        var lr = tpr.Result;
                        Console.WriteLine ("finish with " + lr.Count.ToString () + " machine found");
    
                        foreach (var pr in lr) {
                            Console.WriteLine (pr.Address.ToString ());
            }
    
    });
    
    Console.WriteLine ("execute");
    Console.ReadLine ();
    

提交回复
热议问题