时间:2019-03-07 标签:c#NetworkStreamwrite()和read()

发布于 2024-11-26 14:07:23 字数 276 浏览 1 评论 0原文

我想知道如何阻止 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

两相知 2024-12-03 14:07:24

您可以同时发出 readwrite,如 MSDN 文档

可以在 NetworkStream 类的实例上同时执行读取和写入操作,而无需同步。只要有一个单独的线程用于写操作,一个单独的线程用于读操作,读写线程之间就不会交叉干扰,也不需要同步。

You can issue both read and write simultaneously as stated in the docs at MSDN docs

Read and write operations can be performed simultaneously on an instance of the NetworkStream class without the need for synchronization. As long as there is one unique thread for the write operations and one unique thread for the read operations, there will be no cross-interference between read and write threads and no synchronization is required.

独木成林 2024-12-03 14:07:24

您将需要使用非阻塞读取操作,如下所述: 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

属性 2024-12-03 14:07:24

您可能会在某些时间段查询 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.

迷爱 2024-12-03 14:07:24

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文