title: How to Perform Multiple "Pings" in Parallel using C#
body: <p>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 written a function called <code>AverageRoundtripTime()</code> and it seems to work, however, since I don't know very much about multi-threading, I am wondering if what I've done is okay.  Please take a look at my code and let me know if it's okay or if there's a better way to achieve what I want:</p>
  
  <pre><code>public void Main()
  {
      // Collection of hosts.
      List&lt;String&gt; hosts = new List&lt;String&gt;();
  
      // Add 100 hosts to the collection.
      for (Int32 i = 0; i &lt; 100; ++i) hosts.Add("www.google.com");
  
      // Display the average round-trip time for 100 hosts.
      Console.WriteLine(AverageRoundtripTime(hosts));
  
  }
  
  public Double AverageRoundtripTime(IEnumerable&lt;String&gt; hosts)
  {
      // Collection of threads.
      List&lt;Thread&gt; threads = new List&lt;Thread&gt;();
  
      // Collection of ping replies.
      List&lt;PingReply&gt; pingReplies = new List&lt;PingReply&gt;();
  
      // Loop through all host names.
      foreach (var host in hosts)
      {
          // Create a new thread.
          Thread thread = new Thread(() =&gt;
          {
              // Variable to hold the ping reply.
              PingReply reply = null;
  
              // Create a new Ping object and make sure that it's 
              // disposed after we're finished with it.
              using (Ping ping = new Ping())
              {
                      reply = ping.Send(host);
  
              }
  
              // Get exclusive lock on the pingReplies collection.
              lock (pingReplies)
              {
                  // Add the ping reply to the collection.
                  pingReplies.Add(reply);
  
              }
  
          });
  
          // Add the newly created thread to the theads collection.
          threads.Add(thread);
  
          // Start the thread.
          thread.Start();
  
      }
  
      // Wait for all threads to complete
      foreach (Thread thread in threads)
      {
          thread.Join();
  
      }
  
      // Calculate and return the average round-trip time.
      return pingReplies.Average(x =&gt; x.RoundtripTime);
  
  }
  </code></pre>
  
  <p><strong>Update:</strong></p>
  
  <p>Check out a related question that I asked:</p>
  
  <p><a href="https://stackoverflow.com/questions/13406901/task-parallel-library-code-freezes-in-a-windows-forms-application-works-fine-a">Task Parallel Library Code Freezes in a Windows Forms Application - Works fine as a Windows Console Application</a></p>