首页 > 解决方案 > 将 ConcurrentQueue.Count 与整数进行比较会返回错误的结果

问题描述

我正在编写通常的读写器功能,其中一个主线程排队,几个线程出队。因此,在代码的一部分中,我将我的项目数ConcurrentQueue与某个整数进行比较,我们称之为“maxSize”。尽管.Count返回1maxSize为 10,但queue.Count >= maxSize返回 true。

我尝试使用断点进行调试,只设置一个出队线程,甚至暂停它。这发生在主线程入队之后,并且在几行代码之后,这个比较返回了 1 >= 10 的结果。我确信主线程此时只放置了一项,我确信没有Dequeue()被调用。另外,我尝试过仔细检查锁定,但有时它没有帮助。我想知道可能有一些魔法不允许我以我这样做的方式正确比较值,因为当我在调试器中看到 1 >= 10 为真时,我被撕裂了。


int maxSize = 10;
Timer timer;

ctor(int interval)
{
    queue = new ConcurrentQueue<HttpSessionState>();
    timer = new Timer(TimeSpan.FromSeconds(interval).TotalMilliseconds);
    timer.Elapsed += (sender, args) => PulseIfAvailableForProcessing(true);
}

void Process()
{
    queue.Enqueue(obj);
    // interval here is huge, several minutes
    timer.Start();
    PulseIfAvailableForProcessing(false);
}

bool PulseIfAvailableForProcessing(bool isTimeout)
{
    if (isTimeout)
    {
        ...
    }
    else
    {
        // here 1 >= 10 gives true
        if (queue.Count >= maxSize)
        {
            lock (_dataLock)
            {
                // here in debug queue.Count is still 1, however 1 >= 10 returns false
                if (queue.Count >= maxSize)
                {
                    Pulse();
                }
            }
        }
    }
}

绝望中,我添加了日志记录,我发现在单元测试期间,即使在 lock 语句中,问题也是可重现的。

标签: c#multithreadingconcurrent-queue

解决方案


推荐阅读