The Monitor and Object synchronization method was called from an unsynchronized code block

advertisements

I am checking if my queue is full or not like

lock (SizeQueueProperty.Locker)
{
    while (_queue.Count >= _maxSize)
    {
        SizeQueueProperty.Waiting = true;
        Monitor.Wait(SizeQueueProperty.Locker);
    }
    _queue.Enqueue(item);
    if (_queue.Count == 1)
    {
        // wake up any blocked dequeue
        SizeQueueProperty.Waiting = false;
        Monitor.PulseAll(SizeQueueProperty.Locker);
    }
}

public static class SizeQueueProperty
{
    public volatile static object Locker = new object();
    public volatile static bool Waiting;
}

if is then in another class in another thread checking this code:

if (SizeQueueProperty.Waiting)
{
    Log.Info("Waiting for continue on crawling");
    Monitor.Wait(SizeQueueProperty.Locker);
    ....
    More code
}

...

is is full i would like to wait that queue get empty and then continue with thread execution. But I always get meesage :

Object synchronization method was called from an unsynchronized block of code.

Why?


Wait method from documentation.

Releases the lock on an object and blocks the current thread until it reacquires the lock.

You should call Wait on object only when you hold the lock,

if (SizeQueueProperty.Waiting)
{
    Log.Info("Waiting for continue on crawling");
    Monitor.Wait(SizeQueueProperty.Locker);
}

This code doesn't seems it holds the lock, Does it?