【发布时间】:2012-02-11 16:36:03
【问题描述】:
目前,我正在学习多线程考试。我读了the good threading article of albahari。我对监视器的使用有疑问 - 为什么这里使用循环代替 if?
lock (_locker)
{
while (!_go) //why while and not if?
Monitor.Wait (_locker); // _lock is released
// lock is regained
...
}
我认为,一个 if 就足够了。
恐怕我没有完全理解这篇文章。
//编辑 示例代码:
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 - 感谢您的解释。但我认为,Monitor.Wait 操作只会执行一次。它将等待脉冲信号。所以我暂时看不到任何理由:-(
-
这取决于程序的其余部分,例如
_go的确切含义,以及您何时设置它。 -
嗨 svick - 感谢您的回答。我已经添加了示例。
-
亲,这真的取决于你想等待事件发生多少次。通常,锁定后内存中有某种类型的修改,如果您只想“观察”一次修改,那么您可以使用 if(例如,您发送消息并等待单个响应)。如果您想持续“观察”修改,请在 while 循环中执行(即,您正在监视消息流中是否有大量消息)。
标签: c# multithreading monitor