The call of Monitor.Enter
and Monitor.Exit
must be done by thread themselves. In your code, this is done by the main thread in the process of setting up the two threads. Moreover, that needs to be a monitor of the same object, not two different objects like it is in your case.
To fix this, you need to move the Enter
/Exit
onto the thread into the delegate, and add a common object for the monitor, like this:
object mon = new object();
Thread t = new Thread(()=>{
Monitor.Enter(mon);
Met1(x);
Monitor.Exit(mon);
});
Thread t2 = new Thread(()=>{
Monitor.Enter(mon);
Met2(x,y);
Monitor.Exit(mon);
});
t.start();
t2.start();
Now the t
thread would not be able to call Met1
while Met2
is going, and vice versa.