简体   繁体   English

c#NetworkStream write()和read()

[英]c# NetworkStream write() and read()

I'm wondering how to stop Networkstream.Read() from blocking thread. 我想知道如何阻止Networkstream.Read()阻塞线程。 I have separate thread where NetworkStream.Read() is waiting for data from server. 我有单独的线程,其中NetworkStream.Read()正在等待来自服务器的数据。 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. 但是,当其他线程中有NetworkStream.Read()等待数据时,我无法调用NetworkStream.Write() I can lock NetworkStream each time but NetworkStream.Read() will block thread so I can't send data until read at least 1 byte. 我可以每次锁定NetworkStreamNetworkStream.Read()将阻塞线程,所以在读取至少1个字节之前我不能发送数据。

You can issue both read and write simultaneously as stated in the docs at MSDN docs 您可以按照MSDN文档中的文档中的说明同时发出readwrite

Read and write operations can be performed simultaneously on an instance of the NetworkStream class without the need for synchronization. 可以在NetworkStream类的实例上同时执行读写操作,而无需同步。 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. 只要有一个用于写操作的唯一线程和一个用于读操作的唯一线程,读写线程之间就不会存在交叉干扰,也不需要同步。

您将需要使用非阻塞读取操作,如下所述: http//msdn.microsoft.com/en-us/library/system.net.sockets.networkstream.beginread.aspx

You might query NetworkStream.DataAvailable Property in some time periods and read only if it is true. 您可以在某些时间段内查询NetworkStream.DataAvailable属性,如果为true,则只读。 "If DataAvailable is true, a call to Read returns immediately." “如果DataAvailable为true,则立即调用Read返回。” So you won't block the stream. 所以你不会阻止流。

The NetworkStream class provides methods for sending and receiving data over Stream sockets in blocking mode. NetworkStream类提供了在阻塞模式下通过Stream套接字发送和接收数据的方法。 For more information about blocking versus nonblocking Sockets, see Using an Asynchronous Client Socket 有关阻塞与非阻塞套接字的更多信息,请参阅使用异步客户端套接字

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM