这是多线程设计的正确用法吗?(C#)

inl*_*ine 7 .net c# multithreading

我正在构建一个由服务器和客户端组成的小型聊天程序.服务器保留与其交互的客户端列表.

我在服务器上有两个工作线程.一个处理传入客户端连接.另一个处理传入的客户端消息.

现在,由于两个线程都与名为"clients"的List进行交互,所以我做了类似的事情.

// 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
            */
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是否正确使用锁来防止我的List一次被两个不同的线程更改?

到目前为止,我没有遇到任何问题,但我只是想确保它是正确的.

usr*_*usr 8

这是正确的,但请确保ClientHandler不会长时间保持锁定.它应该永远不会在阻塞时保持锁定(例如,由套接字上的IO操作引起).如果您违反此规则,您将发现您的吞吐量被破坏(仍保持正确性).