Mika
Mika

Reputation: 1245

Multiple threads waiting for NetworkStream.Read

I was wondering what happens if there are more than one thread waiting for data to be available using System.Net.Sockets.NetworkStream.Read:

 numberOfBytesRead = myNetworkStream.Read(myReadBuffer, 0, myReadBuffer.Length);

where myNetworkStream is shared. When data is available, does only one thread see it or all the threads?

Upvotes: 0

Views: 576

Answers (2)

Rafael
Rafael

Reputation: 2817

If your NetworkStream is shared then your threads will interfer with each other. Based in my own experience, each thread can share a Socket, for example if you're doing this for a server, each thread on the server can stay listening on the same socket, then when a client arrives, one thread will start serving it, then after another client arrives, other thread will start serving it and they won't interfer with each other.

Upvotes: 0

Miserable Variable
Miserable Variable

Reputation: 28752

From the documentation:

Use the Write and Read methods for simple single thread synchronous blocking I/O. If you want to process your I/O using separate threads, consider using the BeginWrite and EndWrite methods, or the BeginRead and EndRead methods for communication.

...

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.

So I would say behavior is undefined.

Upvotes: 1

Related Questions