title: Stopping a TcpListener after calling BeginAcceptTcpClient
body: <p>I have this code...</p>
  
  <pre><code>internal static void Start()
  {
      TcpListener listenerSocket = new TcpListener(IPAddress.Any, 32599);
      listenerSocket.Start();
      listenerSocket.BeginAcceptTcpClient(new AsyncCallback(AcceptClient), null);
  }
  </code></pre>
  
  <p>Then my call back function looks like this...</p>
  
  <pre><code>private static void AcceptClient(IAsyncResult asyncResult)
  {
      MessageHandler handler = new MessageHandler(listenerSocket.EndAcceptTcpClient(asyncResult));
      ThreadPool.QueueUserWorkItem((object state) =&gt; handler.Process());
      listenerSocket.BeginAcceptTcpClient(new AsyncCallback(AcceptClient), null);
  }
  </code></pre>
  
  <p>Now, I call BeginAcceptTcpClient, then some time later I want to stop the server. To do this I have been calling TcpListener.Stop(), or TcpListener.Server.Close(). Both of these however execute my AcceptClient function. This then throws an exception when I call EndAcceptTcpClient. What is the best practice way around this? I could just put a flag in to stop the execution of AcceptClient  once I have called stop, but I wonder if I am missing something.</p>
  
  <p><strong>Update 1</strong></p>
  
  <p>Currently I have patched it by changing the code to look like this.</p>
  
  <pre><code>private static void AcceptClient(IAsyncResult asyncResult)
  {
       if (!shutdown)
       {
            MessageHandler handler = new MessageHandler(listenerSocket.EndAcceptTcpClient(asyncResult));
            ThreadPool.QueueUserWorkItem((object state) =&gt; handler.Process());
            listenerSocket.BeginAcceptTcpClient(new AsyncCallback(AcceptClient), null);
       }
  }
  
  private static bool shutdown = false;
  internal static void Stop()
  {
       shutdown = true;
       listenerSocket.Stop();
  }
  </code></pre>
  
  <p>Update 2</p>
  
  <p>I changed it to impliment the answer from Spencer Ruport.</p>
  
  <pre><code>private static void AcceptClient(IAsyncResult asyncResult)
  {
      if (listenerSocket.Server.IsBound)
      {
              MessageHandler handler = new MessageHandler(listenerSocket.EndAcceptTcpClient(asyncResult));
              ThreadPool.QueueUserWorkItem((object state) =&gt; handler.Process());
              listenerSocket.BeginAcceptTcpClient(new AsyncCallback(AcceptClient), null);
      }
  }
  </code></pre>