为什么在Monitor.Wait()中使用lock(object) [英] why in Monitor.Wait() Using of lock(object)
本文介绍了为什么在Monitor.Wait()中使用lock(object)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么在Monitor.Pulse()
和Monitor.Wait()
中使用
Why in Monitor.Pulse()
and Monitor.Wait()
Using of
lock (object)
{
Monitor.Pulse();
// or
Monitor.Wait();
}
但在Monitor.Enter()
&中Monitor.Exit()
不使用吗?
but in Monitor.Enter()
& Monitor.Exit()
do not use?
推荐答案
那是正确的.
方括号Monitor.Enter()
...Monitor.Exit()
的作用类似于lock
语句.lock
或lock
块中的表达式将代码隐式括在获取锁定" ...释放锁定"中的代码.以同样的方式,Monitor.Enter
将所有线程保持在等待队列中,直到当前拥有监视器的线程退出为止,这是已经是线程安全的",它已经已经确保了互斥操作,因为锁会.
相反,必须在同步的代码块内调用Pulse,PulseAll和Wait方法." (Microsoft,请参见 http://msdn.microsoft.com/en-us/library/system.threading.monitor.pulse.aspx [ http://en.wikipedia.org/wiki/种族条件 [^ ]),操作必须以互斥的顺序进行,这由与 Wait
和Pulse
相同的对象上的锁来保证;这个对象本身就是一个队列.将队列同时用作数据容器和锁定对象不是问题,因为该对象是private
(不是public
或internal
).
—SA
That''s correct.
The bracketsMonitor.Enter()
...Monitor.Exit()
play the role analogues to that oflock
statement. The expression under thelock
or in thelock
block implicitly bracket the code in "get lock" ... "release lock". In the same way,Monitor.Enter
will hold all the thread in the wait queue until the thread currently owning a monitor exits, which is "already thread-safe", it already ensures mutual exclusion operation as the lock would.
In contrast, "The Pulse, PulseAll, and Wait methods must be invoked from within a synchronized block of code." (Microsoft, see http://msdn.microsoft.com/en-us/library/system.threading.monitor.pulse.aspx[^]).
Look at the sample from the same help page.
One thread is feeding data in a queue, another thread is consuming the data from the same queue. As a call toPulse
if a non-blocking call; and operation depends on the order of calls toPulse
andWait
. To ensure that this order of operations is not broken be the other thread''s operation interlaced with the other (race condition, http://en.wikipedia.org/wiki/Race_condition[^]), the operations have to be done in mutually exclusive order, that is guaranteed by the lock on the same object asWait
andPulse
; this object is a queue itself. This is not a problem to re-use the queue as a data container and a lock object at the same time, because this object isprivate
(notpublic
orinternal
).
—SA
在问这些问题之前,您是否阅读过文档? :)
在MSDN上的监视器类"页面上:
Do you ever read the documentation before you ask these questions? :)
From the Monitor Class page on MSDN:
Enter和Exit方法提供的功能与C#lock语句(在Visual Basic中为SyncLock)提供的功能相同,不同之处在于,锁和SyncLock在尝试最后将Enter(Object,Boolean)方法重载和Exit方法包装在一起块(在Visual Basic中为Try-Finally)以确保释放了监视器.
The functionality provided by the Enter and Exit methods is identical to that provided by the C# lock statement (SyncLock in Visual Basic), except that lock and SyncLock wrap the Enter(Object, Boolean) method overload and the Exit method in a try-finally block (Try-Finally in Visual Basic) to ensure that the monitor is released.
这篇关于为什么在Monitor.Wait()中使用lock(object)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文