Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Threadsafe class to send messages through socket

I'm trying to implement a module that sends messages to a server via socket. It will be used in a multi threaded environment, so this "Client" object is shared among threads. My question is that should I use a lock block int the Send method to make this class threadsafe? (Probably yes, but I saw a lot of sample codes, where there isn't any locking.)

Here is the simplified version of my MessengerClient class.

public class MessengerClient
{
    private Socket socket;
    public MessengerClient()
    {
        socket = new Socket(SocketType.Stream, ProtocolType.IPv4);
    }

    public void Connect(string host, int port)
    {
        socket.Connect(host, port);
    }

    public void SendMessage(IMessage message)
    {
        var buffer = ObjectConverter.ConvertToByteArray(message);

        var args = new SocketAsyncEventArgs();
        args.Completed += args_Completed;
        args.SetBuffer(buffer, 0, buffer.Length);

        //lock (socket)
        //{
            socket.SendAsync(args);
        //}
    }
}
like image 935
tuta4 Avatar asked May 21 '26 19:05

tuta4


1 Answers

As per the documentation for Socket:

Thread Safety:

Instances of this class are thread safe.

So while thread safe is a somewhat ambiguous term, what it means in this context is that methods of this class, including instance methods, appear atomic from your point of view. You can call a method and know that it will appear as if it ran entirely before or entirely after any methods called in other threads at around the same time. It won't ever execute half of one method, then another, then finish the first (unless it can guarantee that when splitting it up the output is the same as making them completely atomic).

So, in short, you don't need to add lock. The Socket class will ensure that there are no race conditions as a result of calling the method from multiple threads at [or around] the same time.

like image 68
Servy Avatar answered May 23 '26 07:05

Servy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!