How to Call NetworkStream.Read() Without Blocking?

Hongseok Yoon picture Hongseok Yoon · Jun 17, 2009 · Viewed 14.1k times · Source

I'd like to empty read buffer of the socket so I wrote follow code...

byte[] tempBuffer = new byte[1024];
int readCount = 0;
while ((readCount = tcpSocket.GetStream().Read(tempBuffer, 0, tempBuffer.Length)) != 0)
{
    // do with tempBuffer
}

But Read() method is blocked so I added tcpSocket.ReceiveTimeout = 1;. And it works just like before.

As I know, this is usually used in C++. How can I solve this problem?

Answer

Mark Heath picture Mark Heath · Jun 17, 2009

You can use the DataAvailable property to see if there is anything to be read before making a call into the Read method.