tags:

views:

277

answers:

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

There is a better way to do this?

+6  A: 

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.

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.

Jon Skeet
I'll give it a try
Jader Dias
Using a StreamReader.ReadToEnd() should work too?
Jader Dias
@Jader: Only if it's passing text from the other end *and* it will close the socket when it's finished sending. Not good for HTTP KeepAlive connections, for example.
Jon Skeet
It worked!
Jader Dias