according to Eric Gunnerson
Don’t
- Use lock(this)
- Use lock(typeof())
Do Lock on a private variable, not on something the user can see Use “object key = new object()” if you need a private key to lock on
what is the reason??
according to Eric Gunnerson
Don’t
Do Lock on a private variable, not on something the user can see Use “object key = new object()” if you need a private key to lock on
what is the reason??
You should really search for old questions on this before posting a new one. Lock
Also Darin Dimitrov is wrong when he says locks on private variables are dangerous. Locks on private variables serve the purpose of synchronizing the resources of a particular instance of your class. It can happen when you have
}
Because anything that is not private means that could be used from the outside to lock on by someone else or some code that is outside from your control leading to deadlocks.
The best practice is to lock on private static variables, like this:
and then:
private instance variables could also be dangerous since the instance of your class is not something that you as implementer of the class own. It's the consumer of the class that owns the instance.