I have asked a question badly over here Lock on a variable in multiple threads so for clarity I am going to ask it here and hope I can ask it correctly.
classA
Use the lock
keyword to guard code that can be executed simultaneously by more than one thread.
public class ClassA
{
private ClassB b = new ClassB();
public void MethodA()
{
lock (b)
{
// Do anything you want with b here.
}
}
public void MethodB()
{
lock (b)
{
// Do anything you want with b here.
}
}
}
It is important to note that lock
does not guard or lock the object instance used in the statement. Instead, the object is used as a way to identify a section of code that should be prevented from executing if another section using the same object instance is already executing. In other words, you could use any object instance you like in the lock
statements and it would still be safe to access members of ClassB
.