开发者

c# NetworkStream write() and read()

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 thre开发者_StackOverflowad so I can't send data until read at least 1 byte.


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.


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


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜