class Program
{
static object test = new object();
static void Main(string[] args)
{
new Program().test2();
Console.ReadKey();
}
public void test1()
{
lock (test)
{
Console.WriteLine("test1");
}
}
public void test2()
{
lock (test)
{
test1();
Console.WriteLine("test2");
}
}
}
Is the code above supposed to first finish statements in lock statement of test2() then go to the test1()? (i.e. Doesn't the output supposed to be like this? : test2 test1 )
No. The sequence of events (identation represents call stack or logical operations) is:
lock
statement)
lock
statement)
lock
statement)
lock
statement)
It's important to note that monitors are re-entrant - if the current thread already owns the monitor, then another attempt to acquire it will just increase the count, rather than blocking.
If monitors weren't re-entrant, the output wouldn't be "test2, test1" - it would just be deadlock.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With