title: C# TCP Async EndReceive() throws InvalidOperationException ONLY on Windows XP 32-bit
body: <p>I have a simple C# Async Client using a .NET socket that waits for timed messages from a local Java server used for automating commands. The messages come in asynchronously and is written to a ring buffer. This implementation seems to work fine on Windows Vista/7/8 and OSX, but will randomly throw this exception while it's receiving a message from the local Java server:</p>
  
  <blockquote>
    <p>Unhandled Exception: System.InvalidOperationException: EndReceive can only be called once for each asynchronous operation.<br>
    &nbsp;&nbsp;&nbsp;&nbsp;at System.Net.Sockets.Socket.EndReceive(IAsyncResult asyncResult, SocketError&amp; errorCode)<br>
    &nbsp;&nbsp;&nbsp;&nbsp;at System.Net.Sockets.Socket.EndReceive(IAsyncResult asyncResult)<br>
    &nbsp;&nbsp;&nbsp;&nbsp;at SocketTest.Controller.RecvAsyncCallback(IAsyncResult ar)<br>
    &nbsp;&nbsp;&nbsp;&nbsp;at System.Net.LazyAsyncResult.Complete(IntPtr userToken)<br>
    &nbsp;&nbsp;&nbsp;&nbsp;...</p>
  </blockquote>
  
  <p>I've looked online for this error, but have found nothing really helpful. This is the code where it seems to break:</p>
  
  <pre><code>/// &lt;summary&gt;
  /// Callback to receive socket data
  /// &lt;/summary&gt;
  /// &lt;param name="ar"&gt;AsyncResult to pass to End&lt;/param&gt;
  private void RecvAsyncCallback(IAsyncResult ar)
  {
      // The exception will randomly happen on this call
      int bytes = _socket.EndReceive(_recvAsyncResult);
  
      // check for connection closed
      if (bytes == 0)
      {
          return;
      }
  
      _ringBuffer.Write(_buffer, 0, bytes);
  
      // Checks buffer
      CheckBuffer();
  
      _recvAsyncResult = _sock.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, RecvAsyncCallback, null);
  }
  </code></pre>
  
  <p>The error doesn't happen on any particular moment except in the middle of receiving a message. The message itself can be any length for this to happen, and the exception can happen right away, or sometimes even up to a minute of perfect communication. </p>
  
  <p>I'm pretty new with sockets and network communication, and I feel I might be missing something here. I've tested on at least 8 different computers, and the only similarity with the computers that throw this exception is that their OS is Windows XP 32-bit.</p>