从未同步的代码块调用监视器和对象同步方法 [英] Monitor and Object synchronization method was called from an unsynchronized block of code

查看:47
本文介绍了从未同步的代码块调用监视器和对象同步方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在检查我的队列是否已满

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 然后在另一个线程中的另一个类中检查此代码:

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.

为什么?

推荐答案

Wait 文档中的方法.

释放对象上的锁并阻塞当前线程直到它重新获取锁.

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

只有当你持有lock,你才应该在对象上调用Wait

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?

这篇关于从未同步的代码块调用监视器和对象同步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆