时间:2019-03-07 标签:c#NetworkStreamwrite()和read()
我想知道如何阻止 Networkstream.Read() 阻塞线程。我有单独的线程,其中 NetworkStream.Read() 正在等待来自服务器的数据。假设用户按下某个按钮将一些数据发送到服务器。但是当其他线程中有 NetworkStream.Read()
等待数据时,我无法调用 NetworkStream.Write()
。我每次都可以锁定 NetworkStream,但 NetworkStream.Read() 会阻塞线程,因此在读取至少 1 个字节之前我无法发送数据。
I'm wondering how to stop Networkstream.Read()
from blocking thread. I have separate thread where NetworkStream.Read()
is waiting for data from server. Assume that user press some button that send some data to server. But I can't call NetworkStream.Write()
while there is NetworkStream.Read()
in other thread waiting for data. I can lock NetworkStream
each time but NetworkStream.Read()
will block thread so I can't send data until read at least 1 byte.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以同时发出
read
和write
,如 MSDN 文档You can issue both
read
andwrite
simultaneously as stated in the docs at MSDN docs您将需要使用非阻塞读取操作,如下所述: http://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream.beginread.aspx
You will need to use non-blocking read operation as described at : http://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream.beginread.aspx
您可能会在某些时间段查询 NetworkStream.DataAvailable 属性,并且仅在其为 true 时才读取。 “如果 DataAvailable 为 true,则立即返回对 Read 的调用。”所以你不会阻塞流。
You might query NetworkStream.DataAvailable Property in some time periods and read only if it is true. "If DataAvailable is true, a call to Read returns immediately." So you won't block the stream.
NetworkStream 类提供了在阻塞模式下通过 Stream 套接字发送和接收数据的方法。有关阻塞套接字与非阻塞套接字的详细信息,请参阅使用异步客户端套接字
The NetworkStream class provides methods for sending and receiving data over Stream sockets in blocking mode. For more information about blocking versus nonblocking Sockets, see Using an Asynchronous Client Socket