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

前端 未结 6 1443
粉色の甜心
粉色の甜心 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:22

    use the Parallel.For and a ConcurrentBag

        static void Main(string[] args)
        {
            Console.WriteLine(AverageRoundTripTime("www.google.com", 100));
            Console.WriteLine(AverageRoundTripTime("www.stackoverflow.com", 100));
            Console.ReadKey();
        }
    
        static double AverageRoundTripTime(string host, int sampleSize)
        {
            ConcurrentBag values = new ConcurrentBag();
            Parallel.For(1, sampleSize, (x, y) => values.Add(Ping(host)));
            return values.Sum(x => x) / sampleSize;
        }
        static double Ping(string host)
        {
            var reply = new Ping().Send(host);
            if (reply != null)
                return reply.RoundtripTime;
            throw new Exception("denied");
        }
    

提交回复
热议问题