title: Very weird spontaneous disconnect for a System.Net socket
body: <p>I have a System.Net socket that's spontaneously disconnecting, especially if I query its state TWICE in the Visual Studio 2010 debugger.</p>
  
  <p>It's instantiated like this:</p>
  
  <pre><code> _TCPConn = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  </code></pre>
  
  <p>Later I connect and set up a loop to watch its "Connected" property . . . </p>
  
  <pre><code>     _TCPConn.Connect(this.IPAddress, REMOTE_TCP_PORT);
  
        // loop to figure out why / when we're disconnecting ...
        int loops;
        bool bState = false;
        for (loops = 0; loops &lt; 100; loops++)
        {
            bState = _TCPConn.Connected;
            if (!_TCPConn.Connected) 
            {
                break;
            }
            Thread.Sleep(1000);
        }
  </code></pre>
  
  <p>Immediately after the Connect call its Connected property is <strong>true</strong> in the debugger and a network sniffer shows the successful connection with the host.</p>
  
  <p>But if I examine the Connected property a second time in the debugger it shows as <strong>false</strong>.</p>
  
  <p>If I don't set any breakpoints in the loop it gets all the way through the loop (100 seconds) and when it falls out the Connected property is <strong>true</strong> the first time I look at in the debugger and <strong>false</strong> the next time.   </p>
  
  <p>If I let it loop for 10 or 15 seconds and breakpoint, it will be <strong>true</strong> the first time I look in the debugger and <strong>false</strong> the second time I look at it and it will then fall out of the loop at that point, proving that it's not just an artifact of the debugger -  it really is set to false. </p>
  
  <p>When it disconnects there is no associated activity on the network sniffer, i.e., it's not being disconnected by the host.</p>
  
  <p>This is a single-threaded application.   I started looking at this because later on when I tried to use my socket I was often finding it disconnected and was trying to figure out why.    </p>