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

只愿长相守 提交于 2019-12-10 18:37:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!