title: Why my C# socket program has lots of \device\afd handles?
body: <p>I've written a tcp socket prgram that working with sockets asyncoronously.</p>
  
  <p>This is some part of my code:</p>
  
  <pre><code>public void main()
  {
     var e = new SocketAsyncEventArgs();
     e.Completed += new EventHandler&lt;SocketAsyncEventArgs&gt;(e_Completed);
     Task.Factory.StartNew(() =&gt;
     {                        
           allDone.Reset();
           mySocket.AcceptAsync(e);
           allDone.WaitOne();                       
     });
  }
  
  public void e_Completed(object sender, SocketAsyncEventArgs e)
  {
       var socket = (Socket)sender;
       ThreadPool.QueueUserWorkItem(HandleTcpRequest, e.AcceptSocket);
       e.AcceptSocket = null;
       socket.AcceptAsync(e);
  }
  
  public void HandleTcpRequest(object state)
  {
      var mySocket = (Socket)state;
      try
      {
         //do some codes and work with mySocket 
      }
      catch (Exception ex)
      {
      }
      finally
      {
          mySocket.Close();
          mySocket.Dispose();
      }
  }
  </code></pre>
  
  <p>I've seen lots of \device\afd in process explorer in my process.  I've read and searched a lot about this and found that it is related to the Ancillary Function Driver and the Transport Driver Interface.  How can I resolve this handle leak?</p>
  
  <p>==========> edited my code:</p>
  
  <p>Edited to accept only 10 sockets in sync way.</p>
  
  <p>Feel that program is more faster, but when push my finger on Ctrl+F5, find that
  there are more than 10 \device\afd in process explorer and when continuing too push, see more \device\afd, but lower that above code.</p>
  
  <pre><code> mySocket.Listen(10);
   while (true)
   {                                                
        using (Socket so = mySocket.Accept())
        {
              HandleTcpRequest(so);
        }   
   }
  </code></pre>