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? 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#
    – Psylution
    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.

4
  • 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.
    – Psylution
    Oct 16, 2015 at 23:48
  • @neil-patrao Thanks for improving the answer:).
    – ipavlu
    Oct 10, 2017 at 20:38
  • The link you placed to msdn, does not mention any thing regarding concurrency issues
    – eran otzap
    Apr 24, 2019 at 21:28
  • 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:).
    – ipavlu
    Apr 27, 2019 at 17:31

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.