Question

while (TcpClient.Client.Available == 0)
{
    Thread.Sleep(5);
}

Is there a better way to do this?

Was it helpful?

Solution

Absolutely! Just call Read(...) on the stream. That will block until data is available. Unless you really have to use the TcpClient directly, I'd normally do as much as possible on the stream. If you want to use the socket, just call Receive(byte[]) which will block until data is available (or the socket is closed).

Now if you don't want to block, you can use Stream.BeginRead or Socket.BeginReceive to work asynchronously. (Or ReadAsync as of .NET 4.5.)

I personally find Available to be pretty much useless (on both streams and sockets) and looping round with a sleep is definitely inefficient - you don't want to have to context switch the thread when data hasn't come in, and you don't want to have to wait for the sleep to finish when data has come in.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top