title: When NetworkStream.Read(byte[], int, int) needs to return -1, it abort()s the thread it is running on instead?
body: <pre><code>        NetworkStream stream = socket.GetStream();
  
          if (stream.CanRead)
          {
              while (true)
              {
                  int i = stream.Read(buf, 0, 1024);
                  result += Encoding.ASCII.GetString(buf, 0, i);
              }
          }
  </code></pre>
  
  <p>Above code was designed to retrieve message from a <code>TcpClient</code> while running on a separate thread. <code>Read</code> Method works fine until it is supposed to return -1 to indicate there is nothing to read anymore; instead, it just terminates the thread it is running on without any apparent reason - tracing each step using the debugger shows that it just stops running right after that line. </p>
  
  <p>Also I tried encapsulating it with a <code>try ... catch</code> without much success.</p>
  
  <p>What could be causing this? </p>
  
  <p>EDIT: I tried</p>
  
  <pre><code>        NetworkStream stream = socket.GetStream();
  
      if (stream.CanRead)
      {
          while (true)
          {
              int i = stream.Read(buf, 0, 1024);
              if (i == 0)
              {
                  break;
              }
              result += Encoding.ASCII.GetString(buf, 0, i);
          }
      }
  </code></pre>
  
  <p>thanks to @JonSkeet, but the problem is still there. The thread terminates at that <code>read</code> line.</p>
  
  <p>EDIT2: I fixed the code like this and it worked.</p>
  
  <pre><code>    while (stream.DataAvailable)
      {
          int i = stream.Read(buf, 0, 1024);
          result += Encoding.ASCII.GetString(buf, 0, i);
      }
  </code></pre>
  
  <p>I think the problem was simple, I just didn't think thoroughly enough. Thanks everyone for taking a look at this!</p>