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??
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.