17

I know this kinda question got asked several times already here on SO, but not a single thread addressed that exact same problem which we are facing at the moment.

We're basically working on a TCP Server/Client Application, where the Server is written in Java and the Client is written in C#. I'm on the Java Side, and I'm using seperated in and output streams for my buffers.

Our problem is that if the client receives messages from the server and reads those messages asynchronous out the buffer and tries to write something into it during that process an exception is thrown - no surprise.

My question is: What's the way to go in this scenario? Creating seperated streams? We tried that already, but it seemed like C# does not want us to. We are in desperate need of a solution here, and any help is greatly appreciated!

2
  • Basically, you need a solution in C# to read and write simultaneously? the java side is working? Commented Oct 16, 2015 at 23:03
  • Yep, it's working. We just resolved this issue - but still would like to know if there's a way to have seperated streams in c# Commented Oct 16, 2015 at 23:18

1 Answer 1

18

No, it should work. What you need is TcpClient, which you probably already have. From there TcpClient.GetStream(), returning NetworkStream. Then read and write operations can occur concurrently/simultaneously without need for synchronization. So read and write can occur in same time.

What has to be synchronized is multiple concurrent reads. All concurrent reads have to be synchronised by lock(objReads).

Similarly, multiple concurrent writes have to be synchronized by lock(objWrites).

MSDN says, that it is guaranteed.

Please note, that I made it clear, that reads and writes have different locks.

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

4 Comments

We already solved it, the problem was on our side - but thanks for the additional explanation! Now I also know that I just don't need seperated streams.
@neil-patrao Thanks for improving the answer:).
The link you placed to msdn, does not mention any thing regarding concurrency issues
It is buried a little deeper, as TcpClient is returning NetworkStream, where it is expressed in more details, talking about single-thread access, needs for synchronization, etc. but even there it is not exactly well explained. There is a reson why those .NET/C# authors made money on writing books:).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.