I've noticed in virtually all examples I've seen that locks on instances are used as follows
public class Foo {
readonly object locker = new Object();
public void DoSomething() {
lock(locker) {
//...
}
}
public void DoSomethingElse() {
lock(locker) {
//...
}
}
}
This is very useful when multiple threads might have access to the same instance and you want its methods to be atomic relative to each other.
In my experiments, it would work just as well however if I did a lock(this)
rather than having the locker object. Is there something I'm missing or is that perfectly fine?