Re: Socket and multi-threading by Ioannis
Ioannis
Mon May 09 07:13:43 CDT 2005
Mahesh Devjibhai Dhola [MVP] wrote:
> Hi,
>
> Socket class documentation says that it is not thread safe. We understand
> that if do simultaneous sends on ONE socket then it will be a problem (or
> simultaneous receive). Can we create TWO threads on OUR OWN such that one
> will do SEND and one will do RECEIVE using the SAME socket reference? This
> means that two threads WILL BE in the same SOCKET object - one doing receive
> and one doing send. We know we can use asynchronous calls on the socket to
> achieve this but whether we can do this using our own threads. Any pointers
> to official documentation that shows that this is permissible?
If you perform synchronized use of the socket by using thread locks (that is perform a
sending operation with one thread, after the other thread has finished reading), then I
suppose it is OK. However why are you using the Socket class itself for this?
In a book I am currently reading about .NET networking, stream socket communication is
performed in the style:
(get the connection Socket)
get a NetworkStream/create a NetworkStream with the Socket object
create a BinaryWriter and a BinaryReader with the NetworkStream
use the BinaryReader and BinaryWriter for network I/O
Call methods Close() of BinaryReader, BinaryWriter, NetworkStream, (Socket) in turn.