0

On the producer side of my program, while processing the items which will be sent to the collection, they must be checked whether a duplicate one is in the queue, so I need to loop through the BlockingCollection<ConcurrentQueue<Message>> at first place. But I could't find out how to loop through a blocking collection.

public BlockingCollection<ConcurrentQueue<Message>> Collection { get; set; } 
= new BlockingCollection<ConcurrentQueue<Message>>();

foreach(var item in Collection)
{
    //item is ConcurrentQueue<Message>
}

foreach (ConcurrentQueue<Message> queue in Collection)
{
    foreach (var item in queue)    
    {   
        //I don't know if it is efficient but I can reach like that
    }
}  

foreach(var item in Collection.Queue)
{
    // Is there an api something like that?
} 
ibubi
  • 2,469
  • 3
  • 29
  • 50
  • 2
    This is not impossible, but It tries very hard to discourage you from doing this. Because it is fundamentally thread-unsafe, you cannot iterate a collection reliably when other threads are busy modifying it. The guarantee that you won't add the same item twice is already pretty worthless, given that a consuming thread can easily remove the item a nanosecond before you check. And you can't know that it is busy working on the item. This won't happen nearly often enough to ever have a shot at debugging such a flaw. Rather best to review the need for this, it is very smelly. – Hans Passant Oct 31 '17 at 09:31
  • @HansPassant Thank you, adviced posts shows some try eg: https://stackoverflow.com/a/24073395/2289430 The facts you wrote are related with the implementation like that, right? And I want to be sure that I will never ever be safe with these implementations under high concurrency :) – ibubi Oct 31 '17 at 09:46

0 Answers0