If I want to be sure that it will be locked for all threads inside my
application:
The lock object has to be static, if it locks access to static state.
Otherwise it has to be instance, because there’s no need to lock state of one class instance, and prevent other threads to work with another class instance at the same time.
everyone says that the object has to be “readonly” I didn’t found the
reason
Well, it doesn’t have to be. This is just a best practice, which helps you to avoid errors.
Consider this code:
class MyClass
{
private object myLock = new object();
private int state;
public void Method1()
{
lock (myLock)
{
state = // ...
}
}
public void Method2()
{
myLock = new object();
lock (myLock)
{
state = // ...
}
}
}
Here Thread1 can acquire lock via Method1, but Thread2, which is going to execute Method2, will ignore this lock, because lock object was changed => the state can be corrupted.