c# - Monitor.TryEnter 始终返回 true,即使在 Monitor.Enter 之后也是如此

标签 c# .net multithreading synchronization

我想我遗漏了一些关于 Monitor.EnterMonitor.TryEnter 正确行为的信息。这是我编写的一段代码,用于将问题与其余代码分开:

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

结果始终为 true。这里没有惊喜。

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

但这一次也是true。那么 lockObjMonitor.Enter 之后是否被锁定?请给我一些新的看法。

最佳答案

这是因为您在同一个线程中执行此操作。

还要记住 ( 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

关于c# - Monitor.TryEnter 始终返回 true,即使在 Monitor.Enter 之后也是如此,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11154401/

相关文章:

.net - 有没有免费的方法可以将 html 页面转换为带有 .net 的图像

java - 类变量以外的对象的易变性

java - ExecutorService java 可能的线程泄漏

c# - 如何动态添加任意数量的线系列到WPF工具包图表中?

c# - .NET、.Contains() 或 .Count() 哪个更快?

c# - 使用 Unity 跨多种类型注入(inject)相同的 DataContext 实例

c# - 比较 .NET 中的字符串

c++ - 混合松弛和释放-获取内存指令

c# - C# 中的继承和析构函数

c# - 如何有效地检查一条路径是否是 C# 中另一条路径的子路径?