c# NetworkStream write() and read()

mukai picture mukai · Jul 27, 2011 · Viewed 13.5k times · Source

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.

Answer

Bjorn Coltof picture Bjorn Coltof · Jul 27, 2011

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.