Search code examples
c#.netblockingqueueblockingcollection

Wait until a BlockingCollection queue is cleared by a background thread, with a timeout if it takes too long?


In C#, I'm wondering if it's possible to wait until a BlockingCollection is cleared by a background thread, with a timeout if it takes too long.

The temporary code that I have at the moment strikes me as somewhat inelegant (since when is it good practice to use Thread.Sleep?):

while (_blockingCollection.Count > 0 || !_blockingCollection.IsAddingCompleted)
{
    Thread.Sleep(TimeSpan.FromMilliseconds(20));
    // [extra code to break if it takes too long]
}

Solution

  • What if you write something like this in your consuming thread:

    var timeout = TimeSpan.FromMilliseconds(10000);
    T item;
    while (_blockingCollection.TryTake(out item, timeout))
    {
         // do something with item
    }
    // If we end here. Either we have a timeout or we are out of items.
    if (!_blockingCollection.IsAddingCompleted)
       throw MyTimeoutException();