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]
}
_blockingCollection.Count != 0 || !blockingCollection.IsAddingCompleted
(note the use of || instead of &&) – Deus