且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

***的方式来等待TcpClient的数据变为可用?

更新时间:2022-12-31 08:40:30

当然可以!只需拨打阅读(?)在流。这将阻塞,直到数据可用。除非你真正的有无的使用的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.