问题描述
我已经开发出以下列方式脉冲通过监视器通用生产者 - 消费者队列:
I have developed a generic producer-consumer queue which pulses by Monitor in the following way:
排队
public void EnqueueTask(T task)
{
_workerQueue.Enqueue(task);
Monitor.Pulse(_locker);
}
出列:
the dequeue:
private T Dequeue()
{
T dequeueItem;
if (_workerQueue.Count > 0)
{
_workerQueue.TryDequeue(out dequeueItem);
if(dequeueItem!=null)
return dequeueItem;
}
while (_workerQueue.Count == 0)
{
Monitor.Wait(_locker);
}
_workerQueue.TryDequeue(out dequeueItem);
return dequeueItem;
}
等待部分产生以下SynchronizationLockException:
的对象同步方法从代码为
未同步块叫我是否需要同步呢?为什么呢?它是更好地使用ManualResetEvents或.NET 4.0的修身版?
the wait section produces the following SynchronizationLockException :"object synchronization method was called from an unsynchronized block of code"do i need to synch it? why ? Is it better to use ManualResetEvents or the Slim version of .NET 4.0?
推荐答案
是,当前线程需要自己为了监控打电话或者等待
或脉冲
,如记录。 (所以你需要锁定脉冲
为好。)我不知道为什么它所需的细节,但它在Java中的相同。通常我已经找到了我想这样做反正虽然,使调用代码干净。
Yes, the current thread needs to "own" the monitor in order to call either Wait
or Pulse
, as documented. (So you'll need to lock for Pulse
as well.) I don't know the details for why it's required, but it's the same in Java. I've usually found I'd want to do that anyway though, to make the calling code clean.
注意等待
释放显示器本身,然后等待脉冲
,然后重新获取显示器返回之前。
Note that Wait
releases the monitor itself, then waits for the Pulse
, then reacquires the monitor before returning.
由于使用的ManualResetEvent
或的AutoResetEvent
而不是 - 你可以,但我个人更喜欢使用监测
方法,除非我需要一些等待句柄的其他功能(如原子等待任何/所有的多柄)。
As for using ManualResetEvent
or AutoResetEvent
instead - you could, but personally I prefer using the Monitor
methods unless I need some of the other features of wait handles (such as atomically waiting for any/all of multiple handles).
这篇关于确实Monitor.Wait需要同步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!