在下面的代码示例中:
class Program
{
private static int counter = 0;
public static object lockRef = new object();
static void Main(string[] args)
{
var th = new Thread(new ThreadStart(() => {
Thread.Sleep(1000);
while (true)
{
Monitor.Enter(Program.lockRef);
++Program.counter;
Monitor.Exit(Program.lockRef);
}
}));
th.Start();
while (true)
{
Monitor.Enter(Program.lockRef);
if (Program.counter != 100)
{
Console.WriteLine(Program.counter);
}
else
{
break;
}
Monitor.Exit(Program.lockRef);
}
Console.Read();
}
}
为什么即使我对 Monitor 使用锁定,Main 函数中的 while 循环也不会中断? 如果我在 Thread 中添加 Thread.Sleep(1) 而一切都按预期工作,甚至没有 Monitor ......
是否发生得太快以至于 Monitor 类没有足够的时间来锁定?
注意: != 运算符是有意的。我知道我可以将它设置为 < 并解决问题。我试图实现的是看到它与 Monitor 类一起工作,没有它就不能工作。不幸的是,它不是双向的。 谢谢
最佳答案
while 的第一个线程可能会连续调度两次(即 Monitor 可能不公平。)
关于c# - 使用 Monitor.Enter 锁定变量递增,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18700050/