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);
//}
}
}
As per the documentation for Socket:
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. TheSocketclass will ensure that there are no race conditions as a result of calling the method from multiple threads at [or around] the same time.