title: NetworkStream exceptions and return codes
body: <p>I'm trying to educate myself on the intricacies of reading from a NetworkStream, and understanding the various ways in which problems can occur. I have the following code:</p>
  
  <pre class="lang-cs prettyprint-override"><code>    public async Task ReceiveAll()
      {
          var ns = this.tcp.GetStream();
          var readBuffer = new byte[1000];
          while (true)
          {
              int bytesRead;
              try
              {
                  bytesRead = await ns.ReadAsync(readBuffer, 0, readBuffer.Length);
                  if (bytesRead == 0)
                  {
                      // Remote disconnection A?
                      break;
                  }
              }
              catch (IOException)
              {
                  // Remote disconnection B?
                  break;
              }
              catch (ObjectDisposedException)
              {
                  // Local disconnection?
                  break;
              }
  
              /*Do something with readBuffer */
          }
      }
  </code></pre>
  
  <p>I've marked three points in the code where the program says 'something has gone awry, there is no point continuing'. </p>
  
  <p>The 'Local disconnection' isn't exactly something wrong, it will happen when I locally close the socket which is the only way to exit the loop under normal circumstances. I don't think anything else can cause this, so I think I'm safe to just swallow the exception.</p>
  
  <p>The two 'Remote disconnection' points are what I'm not sure about. I know ReadAsync will return 0 if the connection is terminated remotely (A), but the IOException also seems to fire in some circumstances. If my remote client is a C# console, then closing the socket seems to make 'A' happen, and closing the console window seems to be make 'B' happen. I'm not sure I understand what the difference is between these scenarios? </p>
  
  <p>Finally, a bit of a general question, but is there anything glaringly wrong with this bit of code or my above assumptions?</p>
  
  <p>Thanks.</p>
  
  <p>EDIT: In response to my use of ObjectDisposedException to abort out of the loop:</p>
  
  <p>This is what my 'Stop' method looks like (from the same class as above):</p>
  
  <pre><code>    public void Stop()
      {
          this.tcp.Close();
      }
  </code></pre>
  
  <p>This causes the pending 'ReadAsync' to except with ObjectDisposedException. AFAIK there isn't any other way to abort this. Changing this to:</p>
  
  <pre><code>    public void Stop()
      {
          this.tcp.Client.Shutdown(SocketShutdown.Both);
      }
  </code></pre>
  
  <p>Doesn't appear to actually do anything to the pending call, it just continues waiting.</p>