title: Closing server by client request ends with unexpected recursion resulting in ObjectDisposedException
body: <p>I'm experimenting with Sockets, and have built a fairly simple TCP server.</p>
  
  <p>Code available here: <a href="http://pastebin.com/zLRaBc0q" rel="nofollow">http://pastebin.com/zLRaBc0q</a></p>
  
  <p>I have a problem with stopping the Socket server from client. In the pastebin, starting on line <code>136</code> to <code>192</code> is the handler for server termination.</p>
  
  <p>The logic behind is fairly simple:</p>
  
  <ul>
  <li>disconnect the requesting client;</li>
  <li>remove client from the list of connected clients;</li>
  <li>disconnect and remove the remainder of clients;</li>
  <li>close the server;</li>
  <li>remove server from list.</li>
  </ul>
  
  <p>The program executes the above perfectly, but it somehow manages to squeeze in one extra step at the end of it - seems to unexpectedly execute <code>ReceiveCallback</code> (well, it's unexpected to me), and then ending up with <code>ObjectDisposedException</code> for line <code>100</code>:</p>
  
  <pre><code>private static void ReceiveCallback(object sender, SocketAsyncEventArgs e)
  {
      Socket client = (Socket)sender;
      Socket listener = (Socket)e.UserToken;
  
      string message = Encoding.ASCII.GetString(e.Buffer, e.Offset, e.BytesTransferred);
  
      // L100
      //  \/
      IPEndPoint clientCoordinates = client.RemoteEndPoint as IPEndPoint;
      IPEndPoint serverCoordinates = listener.LocalEndPoint as IPEndPoint;  
  
      Console.WriteLine("{0} bytes from {1} on {2}", e.BytesTransferred, clientCoordinates, serverCoordinates);
  </code></pre>
  
  <p>Obviously, that it cannot access at the shutdown process closed <code>client</code>. The problem here is, I don't understand why the program even enters the <code>ReceiveCallback</code> again. I return void after handling <em>quit message</em> without initiating another call to it.</p>
  
  <p>Worth mentioning is that it only happens when there are two clients connected. With one client it stops without problems.</p>
  
  <p>That though, depicts (to me), that it's not the <code>requesting client</code> ending up with <code>ObjectDisposedException</code>, but the other one. That still doesn't help me, because, anyways, I don't understand why there is <code>ReceiveCallback</code> called again - the client was disconnected and should be marked as such before I stop the server.</p>
  
  <p>How do I make the server stop without <code>ObjectDisposedException</code>?</p>
  
  <p>P.S. The parentheses with <em>to me</em> are just sidenotes. Since I'm a newbie to async + threading, I don't understand how some of the behaviors can happen.</p>