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

StackOverflow https://stackoverflow.com/questions/20840853

Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top