新锁内

Car*_*rra 5 c# multithreading locking

我注意到外国程序员的以下代码:

private Client[] clients = new Client[0];

public CreateClients(int count)
{
    lock (clients)
    {
        clients = new Client[count];

        for(int i=0; i<count; i++)
        {
           Client[i] = new Client();//Stripped
        }
     }
 }
Run Code Online (Sandbox Code Playgroud)

这不是完全正确的代码,但我想知道这究竟是做什么的.每次调用此方法时,这会锁定一个新对象吗?

cor*_*iKa 5

要回答你的问题"我想知道这将做什么",请考虑如果两个线程试图这样做会发生什么.

Thread 1: locks on the clients reference, which is `new Client[0]`
   Thread 1 has entered the critical  block
Thread 1: makes a array and assigns it to the clients reference
Thread 2: locks on the clients reference, which is the array just made in thread 1
   Thread 2 has entered the critical block
Run Code Online (Sandbox Code Playgroud)

你知道在关键块中同时有两个线程.那很糟.