Socket.BeginSendTo and Socket.BeginSendFrom on a single Socket instance from multiple threads

Socket.BeginSendTo and Socket.BeginSendFrom on a single Socket instance from multiple threads

Post by Jonas He » Thu, 23 Jun 2005 02:02:04


Is it safe to call socket.BeginSendTo and socket.BeginSendFrom on a
single instance of Socket from two different threads running
simultaneously?

This is required because I need to listen on a certain URI [IP:Port] and
I need to send outgoing messages from that local socket [IP:Port]

something like this:
public class Communicator {
Socket skt = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp );
private Thread listenerThread;
private Thread sendThread;
public Communicator() { }
public void Start() {
listenerThread = new Thread(new ThreadStart(Listen));
sendThread = new Thread(new ThreadStart(Send));
listenerThread.Start();
sendThread.Start();
}
private void Listen() {
while(!bStop) {
skt.BeginReceiveFrom(..);
//wait for AsyncCallback to be called
//using ManualResetEvent for this
}
}
private void Send() {
while(!bStop) {
//send all queued messages
skt.BeginSendTo(..);
//wait for AsyncCallback to be called - that would send an event
//using ManualResetEvent for this
}
}
public void Stop() {
bStop = true
}
 
 
 

Socket.BeginSendTo and Socket.BeginSendFrom on a single Socket instance from multiple threads

Post by Nicholas P » Thu, 23 Jun 2005 02:07:40

Jonas,

The documentation for the Socket class indicate that instances of the
Socket class are thread-safe, so I would say yes, it is safe.

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- XXXX@XXXXX.COM

 
 
 

Socket.BeginSendTo and Socket.BeginSendFrom on a single Socket instance from multiple threads

Post by Jonas He » Thu, 23 Jun 2005 20:10:18

Nicholas,

The documentation says "Any public static members of this type are
thread safe. Any instance members are not guaranteed to be thread safe."

So it doesn't really specifically guarentee thread safety of BeginSendTo
and BeginReceiveFrom.

Any ideas or recommendations?