title: How to End NetworkStream.Read() safely ? (in C# or VB.net)
body: <p>I wrote a class that tries to read byte data sent by a server, and when my app ends, I also want the loop to end, but it appears <code>NetworkStream.Read()</code> just waits if no data is ever available. </p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;
  using System.Net.Sockets;
  using System.Threading;
  using System.Net;
  using System.Threading.Tasks;
  namespace Stream
  {
      class Program
      {
          private static TcpClient client = new TcpClient("127.0.0.1", 80);
          private static NetworkStream stream = client.GetStream();
  
          static void Main(string[] args)
          {
              var p = new Program();
              p.Run();
          }
  
          void Run()
          {
              ThreadPool.QueueUserWorkItem(x =&gt;
              {
                  while (true)
                  {
                      stream.Read(new byte[64], 0, 64);
                  }
              });
  
              client.Close();
              // insert Console.ReadLine(); if you want to see an exception occur.
          }
      }
  }
  </code></pre>
  
  <p>With this code, we'd get</p>
  
  <ol>
  <li><code>System.IO.IOException</code> saying "Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host",</li>
  <li><code>ObjectDisposedException</code> saying "Cannot access a disposed object", or</li>
  <li><code>System.IO.IOException</code> saying "A blocking operation was interrupted by a call to WSACancelBlockingCall". </li>
  </ol>
  
  <p>So how could I safely end this method?</p>