c# NetworkStream write() and read()

北慕城南 提交于 2019-12-07 04:13:01

问题


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.


回答1:


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.




回答2:


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




回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/6843064/c-sharp-networkstream-write-and-read

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!