简体   繁体   中英

BinaryReader and BinaryWriter over NetworkStream

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.

"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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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