I am trying to understand these of monitor in C# and tried out the following program.
Basically, this is all it tries to do:
Thread 1 acquires lock on an object (done in method m)
Thread 2 invokes another method which changes the state of locked object when the lock is still held by Thread 1. (Main thread does this by calling anotherMethod)
Ideally, one would expect that when a lock is held on an object, no other thread can alter its state during the lifetime of the lock. But that doesn't seem to be happening.
class Program
{
private int x = 0;
void Method()
{
lock (this)
{
Thread.Sleep(5000);
}
}
void AnotherMethod()
{
x++;
Console.WriteLine("entered");
}
static void Main(string[] args)
{
Program p = new Program();
Thread t = new Thread(() => p.Method());
t.Start();
p.AnotherMethod();
}
}
What good is a lock if it doesn't freeze the state of object when it is in force?
Also, please help me understand this : if the sole purpose of lock statement is to mark some code as critical section, whats the significance of acquiring lock against an object?