Why does the lock object have to be readonly?
c#, multithreading
Solution
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.
Problem
When implementing a lock, I used to create a private object inside of my class: If I want to be sure that it is locked in the thread that created my class: ``` private object Locker = new object(); ``` If I want to be sure that it will be locked for all threads inside my application: ``` private static object Locker = new object(); ``` But here: Why does the lock object have to be static? and in a number of other questions, everyone says that the object has to be `readonly`. I haven't found the reason - not even in MSDN or JavaDoc. As I use this kind of construction quite often, could someone explain to me why should I use `readonly`? Thanks!