0

I am using GetConsumingEnumerable() to iterate over a BlockingCollection to consume data produced by another thread. I like it because it removes the items from the collection in a foreach, but there are a few cases where the item should not be removed.

Is there a way to cancel the removal of the item from the collection? Or is there a better methodology to achieve what I am doing here?

I have tried just adding the item back in to the collection, but it blows up when the collection has been marked as completed.

private static void iterateQueued()
    {
        while (!queuedCollection.IsCompleted)
        {
            foreach (var t in queuedCollection.GetConsumingEnumerable())
            {
                var movs = (from m in otherCollection
                            where m.ID == t.ID
                            select m).FirstOrDefault();
                if (movs != null) //all set, let t be disposed
                    movs.Things.Add(t); 
                else //no good, keep t for next iteration
                {
                    if (!queuedCollection.IsCompleted) 
                        queuedCollection.TryAdd(t);  //explodes when queuedCollection.CompleteAdding() is called
                    else thwarted++;
                }
            }
        }
    }
user2258854
  • 61
  • 1
  • 1
  • 9
  • Possible duplicate of http://stackoverflow.com/questions/13581945/analogue-of-queue-peek-for-blockingcollection-when-listening-to-consuming-ienu – Ian Mercer May 14 '16 at 05:50
  • The thread-safety guarantee you get from BlockingCollection does have a few strings attached. No, you cannot leave an item in the collection in a thread-safe way. Maybe you can remove it and add it back, albeit it that this has problems of its own like burning 100% core on the same item. There is no santa clause here. – Hans Passant May 14 '16 at 08:31

0 Answers0