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

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

    The ping class has a method SendAsync. This follows the Event-based Asynchronous Programming (EAP) pattern. Check out this article: http://msdn.microsoft.com/en-us/library/ee622454.aspx.

    For a quick example here is a method I have that implements that article in a very basic fashion. You can basically call this as many times as you want and all the pings will be done asychronously.

        class Program
        {
        public static string[] addresses = {"microsoft.com", "yahoo.com", "google.com"};
        static void Main(string[] args)
        {
            List> pingTasks = new List>();
            foreach (var address in addresses)
            {
                pingTasks.Add(PingAsync(address));
            }
    
            //Wait for all the tasks to complete
            Task.WaitAll(pingTasks.ToArray());
    
            //Now you can iterate over your list of pingTasks
            foreach (var pingTask in pingTasks)
            {
                //pingTask.Result is whatever type T was declared in PingAsync
                Console.WriteLine(pingTask.Result.RoundtripTime);
            }
            Console.ReadLine();
        }
    
        static Task PingAsync(string address)
        {
            var tcs = new TaskCompletionSource();
            Ping ping = new Ping();
            ping.PingCompleted += (obj, sender) =>
                {
                    tcs.SetResult(sender.Reply);
                };
            ping.SendAsync(address, new object());
            return tcs.Task;
        }
    }
    

提交回复
热议问题