最好的方式来等待TcpClient的数据变为可用? [英] Best way to wait for TcpClient data to become available?
问题描述
while (TcpClient.Client.Available == 0)
{
Thread.Sleep(5);
}
有没有更好的方式来做到这一点?
Is there a better way to do this?
推荐答案
当然可以!只需拨打阅读(?)
在流。这将阻塞,直到数据可用。除非你真正的有无的使用的TcpClient
直接,我通常做的尽可能的在流。如果你想使用的插座,只需拨打接收(字节[])
这将阻塞,直到数据可用(或关闭套接字)。
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).
现在,如果你不希望阻止,你可以使用 Stream.BeginRead
或 Socket.BeginReceive
来异步工作。 (或 ReadAsync
作为.NET 4.5。)
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.)
我个人觉得可用
是pretty的无用(两个流和插座)和循环圆,睡眠绝对是低效的 - 你不想有上下文切换线程时,数据没有进来,你不希望有等待睡眠来完成,当数据的的的进来了。
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.
这篇关于最好的方式来等待TcpClient的数据变为可用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!