将TryDequeue放入while循环是否安全? [英] Is it safe to put TryDequeue in a while loop?

查看:1063
本文介绍了将TryDequeue放入while循环是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以前没有使用并发队列.

I have not used concurrent queue before.

可以在while循环中按如下方式使用TryDequeue吗?难道这不会永远卡住吗?

Is it OK to use TryDequeue as below, in a while loop? Could this not get stuck forever?

var cq = new ConcurrentQueue<string>();
cq.Enqueue("test");

string retValue;

while(!cq.TryDequeue(out retValue))
{
    // Maybe sleep?
}

//Do rest of code

推荐答案

是的,根据文档,它是安全的,但不建议这样做.

Yes it is safe as per the documentation, but it is not a recommended design.

如果队列在第一次调用TryDequeue时为空,并且此后没有其他线程将数据推送到队列中,那么它可能会永远卡住"(尽管您可以在N次尝试之后或超时后中断一段时间)

It might get "Stuck forever" if the queue was empty at the first call TryDequeue, and if no other thread pushes data in the queue after that point (you could break the while after N attempts or after a timeout, though).

ConcurrentQueue提供了一个 IsEmpty 成员检查队列中是否有项目.检查它比遍历TryDequeue调用(特别是如果队列通常为空)更有效.

ConcurrentQueue offers an IsEmpty member to check if there are items in the Queue. It is much more efficient to check it than to loop over a TryDequeue call (particularly if the queue is generally empty)

可能想要做的是:

while(cq.IsEmpty())
{
    // Maybe sleep / wait / ...
}

if(cq.TryDequeue(out retValue))
{
...
}

如果最后一次调用返回false:另一个您的线程使该项目出队.如果没有其他线程,这是安全的,如果有,则应使用while(TryDequeue)

If this last call returns false: another of your threads dequeued the item. If you don't have other threads, this is safe, if you do, you should use while(TryDequeue)

这篇关于将TryDequeue放入while循环是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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