Monitor.TryEnter总是甚至只是经过Monitor.Enter返回trueTryEnter、Monitor、true、Enter

2023-09-05 04:35:04 作者:愿为你负尽苍生

我觉得我失去了一些关于 Monitor.Enter 的正确行为和 Monitor.TryEnter 。这里是一块code我写了这一问题从的code中的其余部分分隔开:

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);

结果总是。没有惊喜。

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

但是,这一次它也是。所以 lockObj 锁定后 Monitor.Enter 或没有?请给我一些新鲜的看看这个。

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

推荐答案

这是因为,你这样做是在同一个线程。

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

另外请记住,( 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

 
精彩推荐
图片推荐