Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Monitor.TryEnter always returns true even just after Monitor.Enter

I think I am missing something about correct behaviour of Monitor.Enter and Monitor.TryEnter. Here is a piece of code I wrote to separate the issue from the rest of the code:

object lockObj = new object();
bool result = Monitor.TryEnter(lockObj);
Console.Write(result);

Result is always true. No surprises here.

object lockObj = new object();
Monitor.Enter(lockObj);
bool result = Monitor.TryEnter(lockObj);
Console.Write(result);

But this time it is also true. So is lockObj locked after Monitor.Enter or not? Please give me some fresh look at this.

like image 399
rotman Avatar asked Oct 16 '25 13:10

rotman


1 Answers

This is because you are doing this in the same thread.

Also keep in mind that (MSDN):

It is legal for the same thread to invoke Enter more than once without it blocking; however, an equal number of Exit calls must be invoked before other threads waiting on the object will unblock

like image 74
sll Avatar answered Oct 19 '25 01:10

sll