How to fine tune the bufferSize while reading small data from the TcpClient/NetworkStrem? If the bufferSize is big like 1024, 4096 the Read/BeginRead blocks. If I set the bufferSize to 16, 32 it works without blocking.
- Does setting the bufferSize to 1 guarantee there won't be any blocks? Will the performance impact be very bad?
It looks like setting the ReadTimeout to values like 1000, 2000 has no effect over blocking. Is there any other way to make the blocking be short? (NoDelay = true doesn't work)
public static IObservable<byte[]> AsyncReadChunk(this Stream stream, int bufferSize) { var buffer = new byte[bufferSize]; return Observable.FromAsyncPattern<byte[], int, int, int>(stream.BeginRead, stream.EndRead)(buffer, 0, bufferSize) .Select(cbRead => { var dataChunk = new byte[cbRead]; Buffer.BlockCopy(buffer, 0, dataChunk, 0, cbRead); return dataChunk; }); } public static IObservable<byte[]> AsyncRead(this NetworkStream stream, int bufferSize) { return Observable.Defer(() => stream.DataAvailable ? AsyncReadChunk(stream, bufferSize) : Observable.Return(new byte[0])) .Repeat() .TakeWhile((dataChunk, index) => dataChunk.Length > 0); }