Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BinaryReader and BinaryWriter over NetworkStream

Tags:

c#

.net

Is it possible to use a BinaryReader and BinaryWriter at the same time with the same underlying NetworkStream

  1. using a single thread sequentially interlacing reads and writes?
  2. using 1 thread for reading and 1 thread for writing?

(My goal is to simultaneously send and receive data via a TcpClient connection)

So far I've come across two related posts:

One references the NetworkStream 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.

The second references the BinaryReader docs:

Using the underlying stream while reading or while using the BinaryReader can cause data loss and corruption. For example, the same bytes might be read more than once, bytes might be skipped, or character reading might become unpredictable.

I'm not 100% sure how to interpret these quotes and I'm not sure which of my 2 cases above are possible if any.

like image 930
pere57 Avatar asked Mar 13 '18 08:03

pere57


1 Answers

"yes" is the short answer; a NetworkStream essentially acts as a duplex stream, with the read operations completely separate to the write operations. A BinaryReader will only be using the read operations, and BinaryWriter the write operations. Concepts like Length, Position and Seek do not make sense on NetworkStream and are not supported. So: there should be no conflict here using BinaryReader / BinaryWriter. However, at the same time I would probably advise against using them - simply because they usually don't actually add much vs using raw Stream operations, and aren't compatible with arbitrary network protocols. If you're implementing something custom that just uses your code: you'll probably be fine, of course.

The warning about touching the Stream while using BinaryReader/BinaryWriter still very much applies to some other streams - FileStream for example: you could trivially corrupt the data by repositioning the stream while a reader/writer thinks it is in charge - and since there is a single position: this means that reads will impact writes, etc. But: this simply doesn't apply to NetworkStream. In this regard: NetworkStream is the exception, not the rule: in terms of what you usually expect from a Stream, NetworkStream is very unusual.

like image 113
Marc Gravell Avatar answered Nov 13 '22 13:11

Marc Gravell