The following code never return. Debugging shows that the queue.IsCompleted returns false even when the queue is empty. Did I miss anything?
var workers = new Task[1];
using (var queue = new BlockingCollection<QueuePayload>(20))
{
workers[0] = Task.Run(() => Consume(queue));
queue.Add(new QueuePayload{....});
Task.WaitAll(workers);
}
void Consume(BlockingCollection<QueuePayload> queue))
{
while (!queue.IsCompleted)
{
var i = new QueuePayload();
try
{
i = queue.Take();
}
catch (InvalidOperationException)
{
break;
}
......
The property for IsCompleted
at https://msdn.microsoft.com/en-us/library/dd267315(v=vs.110).aspx has the following text:
Whether this collection has been marked as complete for adding and is empty.
Where do you mark the collection as completed? This is not an empty check - it is an empty check with a manual additional switch.
There is accordingly a CompleteAdding()
method that marks that no more items will be added.