title: Difference between NetworkStream.Read() and NetworkStream.BeginRead()?
body: <p>I need to read from <code>NetworkStream</code> which would send data randomly and the size of data packets also keep varying. I am implementing a multi-threaded application where each thread would have its own stream to read from. If there is no data on the stream, the application should keep waiting for the data to arrive. However, if the server is done sending data and has terminated the session, then it should exit out.</p>
  
  <p>Initially I had utilised the <code>Read</code> method to obtain the data from the stream, but it used to block the thread and kept waiting until data appeared on the stream. </p>
  
  <p>The documentation on MSDN suggests,</p>
  
  <blockquote>
    <p>If no data is available for reading,
    the Read method returns 0. If the
    remote host shuts down the connection,
    and all available data has been
    received, the Read method completes
    immediately and return zero bytes.</p>
  </blockquote>
  
  <p>But in my case, I have never got the <code>Read</code> method to return 0 and exit gracefully. It just waits indefinitely. </p>
  
  <p>In my further investigation, I came across <code>BeginRead</code> which watches the stream and invokes a callback method asynchronously, as soon as it receives the data. I have tried to look for various implementations using this approach as well, however, I was unable to identify when would using <code>BeginRead</code> be beneficial as opposed to <code>Read</code>. </p>
  
  <p>As I look at it, <code>BeginRead</code> has just the advantage of having the async call, which would not block the current thread. But in my application, I already have a separate thread to read and process the data from stream, so that wouldn't make much difference for me. </p>
  
  <ul>
  <li><p>Can anyone please help me understand the Wait and Exit mechanism for
  <code>BeginRead</code> and how is it different from <code>Read</code>?</p></li>
  <li><p>What would be the best way to implement the desired functionality?</p></li>
  </ul>