I am creating a small chat program consisting of a server and a client. The server stores a list of clients with which it interacts.
I have two worker threads on the server. One handles incoming client connections. Another handles incoming client messages.
Now, since both threads are interacting with a list called "clients", I did something like this.
// The clients list looks something like this... List<TcpClient> clients; // This is running on one thread. ConnectionHandler() { while(true) { // Wait for client to connect, etc. etc. // Now, add the client to my clients List. lock(clients)clients.Add(myNewClient); } } // This is running on another thread. ClientHandler() { while(true) { lock(clients) { /* This will be handling things like incoming messages and clients disconnecting (clients being removed from the 'clients' List */ } } }
Is this using locks correctly to prevent two different threads from modifying my list?
I have not had any problems with this yet, but I just want to make sure that this is correct.
inline
source share