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

后端 未结 3 1887
死守一世寂寞
死守一世寂寞 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:57

    It's almost always preferable to lock on a private readonly object.

    The difference is that this is generally visible to outside code, which may take a lock on it, i.e. -

    var obj = new YourClass();
    lock(obj)
    {
        ...
    }
    

    ...in which case any attempt inside of YourClass to lock (this) would block.

提交回复
热议问题