Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to wait for TcpClient data to become available?

Tags:

c#

.net

tcpclient

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

Is there a better way to do this?

like image 695
Jader Dias Avatar asked Jul 21 '09 13:07

Jader Dias


1 Answers

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.

like image 112
Jon Skeet Avatar answered Sep 29 '22 02:09

Jon Skeet