如何在不阻塞的情况下调用NetworkStream.Read()?

Hon*_*oon 3 c# sockets networkstream

我想清空套接字的读缓冲区,所以我编写了以下代码...

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

但是Read()方法被阻塞所以我添加了tcpSocket.ReceiveTimeout = 1; .它就像以前一样工作.

据我所知,这通常用在C++中.我怎么解决这个问题?

Mar*_*ath 5

您可以使用DataAvailable属性来查看在调用Read方法之前是否有任何要读取的内容.