Difference between lock(this) and a lock on static object

后端 未结 3 1883
死守一世寂寞
死守一世寂寞 2021-01-04 11:19

Which of the following two code snippets is better to use?

static readonly object _locker = new object();
lock (_locker)

or



        
3条回答
  •  感情败类
    2021-01-04 11:44

    Because you don't want the lock to be accessed from outside the object.

    If you use lock(this) you can get a deadlock:

    void blah() {
       lock(this);
       sleep(200);
    }
    
    //Some other block of code
    
    MyObject a;
    foreach(Mythread m in threads)
    {
       lock(a);
       m.Call(a.blah); //Not the best syntax, but you get the idea.
    }
    

    If you keep the lock inside the object it wouldn't deadlock.

提交回复
热议问题