title: C# TCP Async BeginSend Callback Never Happens
body: <p>I'm working on a game in Unity with C#, and using TCP to exchange data between the server and the client.</p>
  
  <p>I'm using async calls to connect and that seems to work fine. Then a handshake/auth happens as the server prompts the client for client version, client replies, server asks for player's name, player replies, and if all good, server notifies client has been accepted, otherwise connection is closed.</p>
  
  <p>That works most of the time. However, in about 1 in 20, on the very first msg (server->client request for client version, and within a few seconds of game start), the async callback from the first BeginSend <strong>never</strong> gets called, thus halting the auth process. The client does receive the message based on the logging I have in place, and verified via debugging.</p>
  
  <p>The server's call is:</p>
  
  <pre><code>m_isSending = true;
  m_socket.BeginSend(byteArray.buffer, 0, byteArray.arrayLen, SocketFlags.None, new AsyncCallback(EndAsyncWrite), byteArray);
  </code></pre>
  
  <p>I've added m_isSending to help more easily debug/track whether a message is being sent to confirm if the callback has been called.</p>
  
  <p>with EndAsyncWrite being:</p>
  
  <pre><code>protected void EndAsyncWrite(IAsyncResult iar)
  {
          m_isSending = false;
          m_socket.EndSend(iar);
          ByteArray byteArray = (iar.AsyncState as ByteArray);
          //Add prev msg's ByteArray to await recycling
          lock (m_byteArraysAwaitingRecycle)
          {
              m_byteArraysAwaitingRecycle.Add(byteArray);
          }
  }
  </code></pre>
  
  <p>In those 1 in 20 situations, m_isSending will still be true even after the client has received and processed the message. I've poked around in the debugger, but due to, what I assume is Unity's utilizing of mono, can't peer too far in. I have however found the message in the socket's writeQ (which I assume is the queue for writing). Normally it is empty, so I'm wondering if it might be able to shed some light into why the callback isn't being called.
  <a href="http://i.imgur.com/Ew3o6Z3.png" rel="nofollow">Watch Snippet</a>. The only entry present is the message that was sent and the client received.</p>
  
  <p>Other info: nagle's is disable, blocking is set to true. The other 19/20 tries seem to work alright, with no changes. I'm currently testing with localhost as destination.</p>
  
  <p>So I'm pretty confused as I'm doing everything properly as far as I can tell. Why wouldn't the callback get called? Any ideas? Any suggestions? Is there any way to work around this?</p>