title: TcpClient.GetStream().DataAvailable returns false, but stream has more data
body: <p>So, it would seem that a blocking Read() can return before it is done receiving all of the data being sent to it. In turn we wrap the Read() with a loop that is controlled by the DataAvailable value from the stream in question. The problem is that you can receive more data while in this while loop, but there is no behind the scenes processing going on to let the system know this. Most of the solutions I have found to this on the net have not been applicable in one way or another to me.</p>
  
  <p>What I have ended up doing is as the last step in my loop, I do a simple Thread.Sleep(1) after reading each block from the stream. This appears to give the system time to update and I am not getting accurate results but this seems a bit hacky and quite a bit 'circumstantial' for a solution.</p>
  
  <p>Here is a list of the circumstances I am dealing with: Single TCP Connection between an IIS Application and a standalone application, both written in C# for send/receive communication. It sends a request and then waits for a response. This request is initiated by an HTTP request, but I am not having this issue reading data from the HTTP Request, it is after the fact.</p>
  
  <p>Here is the basic code for handling an incoming connection</p>
  
  <pre><code>protected void OnClientCommunication(TcpClient oClient)
  {
      NetworkStream stream = oClient.GetStream();
      MemoryStream msIn = new MemoryStream();
  
      byte[] aMessage = new byte[4096];
      int iBytesRead = 0;
  
      while ( stream.DataAvailable )
      {
          int iRead = stream.Read(aMessage, 0, aMessage.Length);
          iBytesRead += iRead;
          msIn.Write(aMessage, 0, iRead);
          Thread.Sleep(1);
      }
      MemoryStream msOut = new MemoryStream();
  
      // .. Do some processing adding data to the msOut stream
  
      msOut.WriteTo(stream);
      stream.Flush();
  
      oClient.Close();
  }
  </code></pre>
  
  <p>All feedback welcome for a better solution or just a thumbs up on needing to give that Sleep(1) a go to allow things to update properly before we check the DataAvailable value.</p>
  
  <p>Guess I am hoping after 2 years that the answer to <a href="https://stackoverflow.com/questions/166530/does-networkstream-dataavailable-see-buffered-data" title="this">this question</a> isn't how things still are :)</p>