There is a class like so:
public class A{
public B classB { get; set; }
...
}
A is instantiated somewhere as classA.
classA.classB is set and modified by codes I have no control of, those codes may be on different threads.
Now I want to modify classA.classB on the my thread.
Do I need to 1:
lock(classA) lock(classA.classB) {
//my codes that modifies classA.classB
}
Or 2:
lock(classA.classB){
//my codes that modifies classA.classB
}
Basically the question is: Is containing class automatically locked if I lock its members, or it doesn't work like that at all.
Please do NOT tell me:
Well you should use a locking object or a mutex, it may be a solution but it's not related to the question.
Is containing class automatically locked if I lock its members, or it doesn't work like that at all.
It doesn't work like that at all. A lock
does not do anything besides checking if the very same object reference is already locked, waiting until it's not and then locking it, removing the lock when the block is over. It does not imply anything else besides that one bit of information: is it locked or is it not.
Specifically, it does not lock any members, types or other things. It locks exactly the object you give. And a lock does not do anything except giving the information that a lock already exists if asked. It does not prevent code from accessing the object, reading, writing, Disposing, or whatever.
Your question reads a little bit like you expect a lock
to have an effect besides interacting with other lock
blocks. It does not.
So you should have a completely separate object to lock
on, because bad things can happen if you use an object that is also used for another purpose and publicly available. As you gain nothing from using this
or your class object, because lock
does nothing extra, you really have nothing to gain from not following the best practice guidelines.
classA.classB is set and modified by codes I have no control of, those codes may be on different threads.
Now I want to modify classA.classB on the my thread.
You are f... rankly in a bad position. There is no solution to this. You cannot lock
something that way. It's not one-sided. If the other code is not using the same lock you do... they won't care for your lock. A lock
is like a signal. A red light. You can put a red light wherever you want, if the other driver does not know or does not care, there is nothing you can do.
Your only option would be to take control of the classB implementation and make sure it's thread-safe internally.