Is Stream.Write thread safe?

I am working on a client / server library for an obsolete RPC implementation and have run into problems when the client sometimes freezes, waiting for a response to the RPC request message. It turns out that the real problem was in my message framing code (I didnโ€™t correctly process message borders when reading data from the underlying NetworkStream ), but also made me suspicious of the code that I used to send data over the network, in particular, when the server An RPC sends a large amount of data to a client as a result of an RPC client request.

My send code uses BinaryWriter to write the complete โ€œmessageโ€ to the underlying NetworkStream . The RPC protocol also implements the heartbeat algorithm, where the RPC server sends PING messages every 15 seconds. The pins are sent in a separate stream, so, at least theoretically, ping can be sent while the server is in the middle of streaming a large response back to the client.

Suppose I have a Send method as follows, where stream is NetworkStream :

 public void Send(Message message) { //Write the message to a temporary stream so we can send it all-at-once MemoryStream tempStream = new MemoryStream(); message.WriteToStream(tempStream); //Write the serialized message to the stream. //The BinaryWriter is a little redundant in this //simplified example, but here because //the production code uses it. byte[] data = tempStream.ToArray(); BinaryWriter bw = new BinaryWriter(stream); bw.Write(data, 0, data.Length); bw.Flush(); } 

So, I have a question, is the call to bw.Write (and the call to the stream Write method meant) is atomic? That is, if a long Write is still running in the sending stream, and the heartbeat stream starts and sends a PING message whether this stream will block until the original Write call is completed, or do I need to add explicit synchronization with the Send method to prevent the two Send calls from merging flow?

+6
multithreading c # networking
source share
3 answers

Any public static (common in Visual Basic) members of this type are threads safe. Any members of the instance are not guaranteed reliable flow.

From Stream Class , so no it is not guaranteed.

+8
source share

It is not documented as atomic. I would not assume that this would definitely wrap this material around a custom locking mechanism. Basically, the whole Send method basically requires locking.

+2
source share

You must block recording in both threads. Afair writer is not thread safe.

Check the MSDN for "Monitor" and "Mutex."

0
source share

All Articles