title: Closing a NetworkStream after calling BeginRead() in C#
body: <p>I have implemented a system that mimics the DataReceived event of a serial port, whereby the reading of data from a TCPClient object's NetworkStream is triggered by using the BeginRead() method as follows:</p>
  
  <pre><code>TcpClient server = new TcpClient();
  server.Connect(IPAddress.Parse(ip), 10001);
  server.GetStream().BeginRead(buffer, 0, buffer.Length, new AsyncCallback(DataReceived), server.GetStream());
  </code></pre>
  
  <p>which calls the following method from another thread:</p>
  
  <pre><code> private void DataReceived(IAsyncResult result)
      {
          res = result;
          server.GetStream().EndRead(result);
  
          //append received data to the string buffer
          stringBuffer += System.Text.ASCIIEncoding.ASCII.GetString(buffer);
  
          //clear the byte array
          Array.Clear(buffer, 0, buffer.Length);
  
          //trigger the parser
          waitHandle.Set();
  
          server.GetStream().BeginRead(buffer, 0, buffer.Length, new AsyncCallback(DataReceived), buffer);
      }
  </code></pre>
  
  <p>This appears to work correctly. I can send and receive data to a device on the network without issue. However, when I attempt to disconnect using the following method, the program crashes:</p>
  
  <pre><code>public override void disconnect()
  {
      server.Close();
  }
  </code></pre>
  
  <p>It throws the following error:</p>
  
  <pre><code>A first chance exception of type 'System.ObjectDisposedException' occurred in System.dll
  </code></pre>
  
  <p>I have also tried implementing the disconnect method as follows:</p>
  
  <pre><code>server.GetStream().Close();
  </code></pre>
  
  <p>but this results in the following error:</p>
  
  <pre><code>A first chance exception of type 'System.InvalidOperationException' occurred in System.dll
  </code></pre>
  
  <p>I assume this has something to do with the fact that the BeginRead() method has been called and the EndRead() method has not. If that is the case how can I close the stream without it crashing?</p>