I wrote the following function to implement the timeout function using the asynchronous NetworkStream reading functions ( BeginRead and EndRead ). It works fine until I comment out the line Trace.WriteLine("bytesRead: " + bytesRead); . Why?
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."); }
Just in case you are interested, I have to do this because I will eventually need to configure the .NET Compact Framework 3.5 and do not support the NetworkStream.ReadTimeout and NetworkStream.WriteTimeout properties.
Verax source share