.Net 中的 ConcurrentQueue 和 BlockingCollection 有什么区别? [英] What are the differences between ConcurrentQueue and BlockingCollection in .Net?

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

问题描述

.Net 中的 ConcurrentQueueBlockingCollection 有什么区别?

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 有一个 Take 方法,如果没有东西可以拿走,会阻塞消费者,然后等待供生产者方提供项目.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 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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