Socket.BeginSendTo and Socket.BeginSendFrom on a single Socket instancefrom multiple threads

J

Jonas Hei

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
}
 
N

Nicholas Paldino [.NET/C# MVP]

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.
 
J

Jonas Hei

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?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top