I was looking at the answer for not using "this" in the lock, if the instance is publicly accessible. I tried below example , I was thinking Method1 will be not called since lock is already acquired in Main method on the instance. But Method1 is called Method2 wait indefinitely. Explanation for the same will be appreciated .
class Program
{
static void Main(string[] args)
{
Tracker tracker = new Tracker();
lock (tracker)
{
Parallel.Invoke(() => tracker.Method1(),
() => tracker.Method2());
}
}
}
class Tracker
{
private int number = 6;
public void Method1()
{
lock (this)
{
number *= 5;
Console.WriteLine("Method1: " + number);
number /= 4;
Console.WriteLine("Method1: " + number);
}
}
public void Method2()
{
lock (this)
{
number *= 3;
Console.WriteLine("Method2: " + number);
number /= 2;
Console.WriteLine("Method2: " + number);
}
}
}