2

I'm using a StreamReader to read from a TcpSocket, and a StreamWriter to write to that TcpSocket. I would like to have the reading code in one thread and the writing code in another. How do I do this in a thread-safe manner?

If I do the following, then I guess the writer thread will be blocked in many cases:

lock (tcpClient) { streamReader.ReadLine(); } 

Here would be the writer code:

lock (tcpClient) { streamWriter.WriteLine(line); } 

1 Answer 1

4

It is safe to send on one thread and receive on the other thread.

So you can do this in one thread:

streamReader.ReadLine(); 

and this in another thread:

streamWriter.WriteLine(line); 

without having to lock the tcpClient.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer, but is this documented anywhere? MSDN says that the instance members of StreamReader and StreamWriter and not guaranteed to be thread-safe.
I'm not sure this is documented anywhere. The thread-safety statement is just standard boilerplate that appears for almost all classes. The .NET Socket class is a wrapper around the Winsock API, so a StreamWriter.WriteLine call eventually results in a call to the Winsock send function which places the bytes in the send buffer. The StreamReader.ReadLine() call results in a call to the Winsock receive function which reads bytes from the receive buffer. So there is no resource shared as long as only one thread ever writes to the send buffer and one ever reads from the receive buffer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.