collections – Iterating ConcurrentQueue<T> – Education Career Blog

Is this a safe way of iterating ConcurrentQueue<T>?

while (cq.GetEnumerator().MoveNext())
{
    IIndexTask task;
    if (cq.TryDequeue(out task))
        task.Execute(service);
}

,

Just do this instead…

IIndexTask task;
while (cq.TryDequeue(out task))
{
    task.Execute(service);
}

Leave a Comment