c# - Threadsafe class to send messages through socket -



c# - Threadsafe class to send messages through socket -

i'm trying implement module sends messages server via socket. used in multi threaded environment, "client" object shared among threads. question should utilize lock block int send method create class threadsafe? (probably yes, saw lot of sample codes, there isn't locking.)

here simplified version of 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 socket:

thread safety:

instances of class thread safe.

so while thread safe ambiguous term, means in context methods of class, including instance methods, appear atomic point of view. can phone call method , know appear if ran exclusively before or exclusively after methods called in other threads @ around same time. won't ever execute half of 1 method, another, finish first (unless can guarantee when splitting output same making them atomic).

so, in short, don't need add together lock. socket class ensure there no race conditions result of calling method multiple threads @ [or around] same time.

c# .net multithreading sockets

Comments

Popular posts from this blog

web services - java.lang.NoClassDefFoundError: Could not initialize class net.sf.cglib.proxy.Enhancer -

Accessing MATLAB's unicode strings from C -

javascript - mongodb won't find my schema method in nested container -