问题
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.
回答1:
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
回答2:
The same thread that has already acquired a monitor is always allow to reaquire it (to allow for re-enterant code).
来源:https://stackoverflow.com/questions/11154401/monitor-tryenter-always-returns-true-even-just-after-monitor-enter