Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

Is there a better way to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
558 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...