目前,我正在学习多线程考试。我读the good threading article of albahari。我在监视器使用中遇到了一个问题 - 为什么在这里使用循环代替if?Monitor.Wait - while or if?
lock (_locker)
{
while (!_go) //why while and not if?
Monitor.Wait (_locker); // _lock is released
// lock is regained
...
}
我认为,如果将是足够的。
恐怕,我完全不理解这篇文章。
//编辑 例码:
class SimpleWaitPulse
{
static readonly object _locker = new object();
static bool _go;
static void Main()
{ // The new thread will block
new Thread (Work).Start(); // because _go==false.
Console.ReadLine(); // Wait for user to hit Enter
lock (_locker) // Let's now wake up the thread by
{ // setting _go=true and pulsing.
_go = true;
Monitor.Pulse (_locker);
}
}
static void Work()
{
lock (_locker)
while (!_go)
Monitor.Wait (_locker); // Lock is released while we’re waiting
Console.WriteLine ("Woken!!!");
}
}
“If”只检查一次。 “while”循环将继续检查。如果不等。等待。 – DOK 2012-01-16 19:14:21
Hi DOK - 感谢您的解释。但是我认为,Monitor.Wait操作只会执行一次。它将等待脉冲信号。所以我没有看到一段时间的理由:-( – bitsmuggler 2012-01-16 19:18:16
它取决于程序的其余部分,像'_go'究竟是什么意思,你什么时候设置它 – svick 2012-01-16 19:21:39