Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

does Monitor.Wait Needs synchronization?

I have developed a generic producer-consumer queue which pulses by Monitor in the following way:

the enqueue :

    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;
    }

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?

like image 814
user437631 Avatar asked Sep 26 '10 13:09

user437631


People also ask

What does monitor Wait do?

Wait(Object, TimeSpan, Boolean) Releases the lock on an object and blocks the current thread until it reacquires the lock. If the specified time-out interval elapses, the thread enters the ready queue.

When a monitor wait is called the thread goes into what state?

6 Answers. Show activity on this post. A thread goes to wait state once it calls wait() on an Object. This is called Waiting State.

What is a monitor in Java thread?

Monitor is a synchronization construct that allows threads to have both mutual exclusion and the ability to wait (block) for a certain condition to become true. Monitors also have a mechanism for signaling other threads that their condition has been met. It is an entity that possesses both a lock and a wait set.

What does the C# method monitor PulseAll () do?

Enter method does not protect variable x at all. What does the C# method Monitor. PulseAll() do? Move all threads in waiting state into ready state.


1 Answers

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.

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).

like image 97
Jon Skeet Avatar answered Oct 05 '22 07:10

Jon Skeet