title: Asynchronous code that works in Console but not in Windows Forms
body: <p>I am trying to write an application the is constantly searching for host on a lan.  When I run this as a console as the countdown.Wait() seems to work fine.  However when I bring the code into a windows form the countdown.Signal() does not seem to decrement its counter.  Not sure what the problem is.</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.ComponentModel;
  using System.Data;
  using System.Drawing;
  using System.Linq;
  using System.Text;
  using System.Windows.Forms;
  using System.Net.NetworkInformation;
  using System.Diagnostics;
  using System.Net;
  using System.Threading;
  
  namespace Multi_Threaded
  {
      public partial class Form1 : Form
      {
  
      public Form1()
      {
          InitializeComponent();
      }
  
      private void Form1_Load(object sender, EventArgs e)
      {
          PortScanner ps = new PortScanner();
          ps.ProbeCompleted += new PingProbeCompleted(ps_ProbeCompleted);
  
          ps.run_ping_probe();
      }
  
      void ps_ProbeCompleted(object sender, PingProbeCompletedArguments e)
      {
          MessageBox.Show("I found " + e.ip_adresses_list_of_host.Count.ToString() + "host(s)");
      }
  }
  
  public delegate void PingProbeCompleted(object sender,PingProbeCompletedArguments e);
  public class PingProbeCompletedArguments : EventArgs
  {
      public List&lt;string&gt; ip_adresses_list_of_host;
  }
  public class PortScanner
  {
      public event PingProbeCompleted ProbeCompleted;
      static List&lt;string&gt; ip_adresses = new List&lt;string&gt;();
  
      static CountdownEvent countdown;
  
      public void run_ping_probe()
      {
          ip_adresses.Clear();
  
          countdown = new CountdownEvent(1);
  
          string ipBase = "10.125.";
          for (int sub = 0; sub &lt; 14; sub++)
          {
              for (int i = 1; i &lt; 255; i++)
              {
                  string ip = ipBase + sub.ToString() + "." + i.ToString();
                  Ping p = new Ping();
                  p.PingCompleted += new PingCompletedEventHandler(p_PingCompleted);
                  countdown.AddCount();
                  p.SendAsync(ip, 100, ip);
              }
          }
          countdown.Signal();
          countdown.Wait();
          PingProbeCompletedArguments e = new PingProbeCompletedArguments();
          e.ip_adresses_list_of_host = ip_adresses;
          ProbeCompleted(this, e);
  
      }
  
      private void p_PingCompleted(object sender, PingCompletedEventArgs e)
      {
          string ip = (string)e.UserState;
          if (e.Reply.Status == IPStatus.Success)
          {
              ip_adresses.Add(ip + "\t" + e.Reply.RoundtripTime + " ms");
          }
          countdown.Signal();
      }
  }
  </code></pre>