Is it safe to use a BinaryReader and a BinaryWriter derived from the same stream source in separate threads?

*爱你&永不变心* 提交于 2019-12-12 06:47:20

问题


I have a scenario with related but different questions. So it may look like a duplicated post but it’s not

I’m working on a class that uses a TcpClient eventually created on the UI thread to read and write data. When the TcpClient is created the design is to connect to a server and create a BinaryReader and BinaryWriter immediately.

The BinaryReader is used on a dedicated thread that does a blocking read. When data arrives I generate an event and pass the data for processing. Rinse and repeat.

The BinaryWriter is used when data arrives on another thread. Right now it happens to be the UI thread, but it doesn’t have to be. One thing that is known is that it won’t be the same thread that the blocking reader is running.

Only one process will access either stream handler at a time so I don’t have to worry about two threads hitting the BinaryWriter at once, but locking will be added.

This is working, but since threading is hard I don’t want to just assume this is sound design. I have other questions concerning the lifetimes of them that will be asked separately.


回答1:


Pretty unclear, always post a snippet. If they wrap the NetworkStream you get from TcpClient.GetStream() then there is no problem. Explicitly mentioned in the MSDN article for NetworkStream:

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.



来源:https://stackoverflow.com/questions/20840853/is-it-safe-to-use-a-binaryreader-and-a-binarywriter-derived-from-the-same-stream

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