問題描述
為什麼 lock(objLock) 比 lock(this) 好 (Why is it better to lock(objLock) than lock(this))
Possible Duplicates: Why is lock(this) {...} bad?
In C# it is common to use lock(objLock) where objLock is an object created simply for the purpose of locking.
Why is this preferable to lock(this)? What are the negative implications of lock(this) other than taking a lock out on the class itself?
‑‑‑‑‑
參考解法
方法 1:
Because something else could lock the instance, then you'd have a deadlock.
If you lock on the object you've created specifically for that purpose, you know you're in complete control, and nothing else is going to lock on it unexpectedly.
方法 2:
If you lock anything public, then both the class and some other class can try to get a lock. It's easy enough to create a sync object, and always preferrable;
private syncLock = new Object();
(by miguel、Winston Smith、Steve Cooper)