Monitor.TryEnter总是甚至只是经过Monitor.Enter返回true [英] Monitor.TryEnter always returns true even just after Monitor.Enter

查看:653
本文介绍了Monitor.TryEnter总是甚至只是经过Monitor.Enter返回true的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得我失去了一些关于 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

这篇关于Monitor.TryEnter总是甚至只是经过Monitor.Enter返回true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆