title: Implementing a timeout with NetworkStream.BeginRead and NetworkStream.EndRead
body: <p>I've written the following function to implement a timeout feature using <code>NetworkStream</code>'s asynchronous read functions (<code>BeginRead</code> and <code>EndRead</code>).  It works fine until I comment out the line <code>Trace.WriteLine("bytesRead: " + bytesRead);</code>.  Why?</p>
  
  <pre><code>private int SynchronousRead(byte[] buffer, int count)
  {
      int bytesRead = 0;
      bool success = false;
      IAsyncResult result = null;
  
      result = _stream.BeginRead(
          buffer, 0, count,
          delegate(IAsyncResult r)
          {
              bytesRead = _stream.EndRead(r);
          },
          null);
  
      success = result.AsyncWaitHandle.WaitOne(_ioTmeoutInMilliseconds, false);
  
      if (!success)
      {
          throw new TimeoutException("Could not read in the specfied timeout.");
      }
  
      //If I remove this line, bytesRead is always 0
      Trace.WriteLine("bytesRead: " + bytesRead);
  
      return bytesRead;
  }
  </code></pre>
  
  <p>Just in case you're wondering, I have to do this because I will eventually need to target the .Net Compact Framework 3.5 and it doesn't support the <code>NetworkStream.ReadTimeout</code> and <code>NetworkStream.WriteTimeout</code> properties.</p>