What is the difference (if any) between using
void MethodName()
{
lock(this)
{
// (...)
}
}
or
private object o = new object();
void MethodName()
{
lock(o)
{
// (...)
}
}
?
Is there a difference in performance? Style? Behaviour?
The difference is that anyone can lock on your instance, but only you can lock on a private object.
This helps prevent deadlocks.
For example:
Let’s say that Microsoft used
lock(this)in theControlclass.Then, if someone else locks on a
Controlinstance, his lock would prevent the code inControlfrom running, which is not what he wants.This is particularly bad if you lock on types that are shared across AppDomains