本文介绍了.Net中的ConcurrentQueue和BlockingCollection之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

.Net中 ConcurrentQueue BlockingCollection 之间有什么区别?

What are the differences between ConcurrentQueue and BlockingCollection in .Net?

为什么 BlockingCollection 最适合生产者 - 消费者操作,当它可以通过 ConcurrentQueue 完成时?我必须改进以下代码中的任何内容吗?

Why BlockingCollection is best for producer-consumer operation when it can be done through ConcurrentQueue? Do I have to improve anything in the following code?

MessageSlotMachineGameStartOrAndStatusUpdate msg;

while (!aCancellationToken.IsCancellationRequested)
{
    try
    {
        this.isStillConsumingMsg = true;
        Boolean takeResult = this.msgQueue.TryTake(out msg, this.msgConsumeTimeOut, aCancellationToken);
        if (takeResult)
        {
            if (msg != null)
            {
                this.ProcessMessage(msg);
            }
        }
        else
        {
            break;
        }
    }
    catch (OperationCanceledException err)
    {
        EngineManager.AddExceptionLog(err, "Signal Operation Canceled");
    }
    catch (Exception err)
    {
        EngineManager.AddExceptionLog(err, "Signal exception");
    }
    finally
    {
        this.isStillConsumingMsg = false;
    }
}


推荐答案

BlockingCollection 有一个采取方法,如果没有东西需要采取措施阻止消费者,并等待生产者提供一个物品。 ConcurrentQueue 缺少这样的方法 - 如果它是空的,消费者需要处理等待,并且生产者需要提供非空通知。

BlockingCollection has a Take method that would block the consumer if there is nothing to take, and wait for a producer side to provide an item. ConcurrentQueue lacks such method - if it is empty, the consumer would need to handle the wait, and the producer would need to provide a non-empty notification.

这篇关于.Net中的ConcurrentQueue和BlockingCollection之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 21:18