C# 等待 TcpClient 数据可用的最佳方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1159264/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best way to wait for TcpClient data to become available?
提问by Jader Dias
while (TcpClient.Client.Available == 0)
{
Thread.Sleep(5);
}
Is there a better way to do this?
有一个更好的方法吗?
采纳答案by Jon Skeet
Absolutely! Just call Read(...)
on the stream. That will block until data is available. Unless you really haveto 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).
绝对地!只需调用Read(...)
流。这将阻塞,直到数据可用。除非您真的必须TcpClient
直接使用 ,否则我通常会在流中尽可能多地使用。如果要使用套接字,只需调用Receive(byte[])
which 将阻塞,直到数据可用(或套接字关闭)。
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.)
现在,如果您不想阻塞,则可以使用Stream.BeginRead
或Socket.BeginReceive
异步工作。(或ReadAsync
从 .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 hascome in.
我个人发现Available
它几乎没用(在流和套接字上)并且循环睡眠绝对是低效的 - 当数据没有进入时,您不想必须上下文切换线程,并且您不想希望有等待睡眠到结束时的数据已经进来了。