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++;
}
}
}
}