locked
Why would BlockingCollection.TryTake() return false? RRS feed

  • Question

  • Hi,

    Maybe I'm misunderstanding how BlockingCollection works exactly, but I have the following piece of code:

     

    if (!dataQueue.TryTake(out dataBuffer, timeout, cancellationToken))
    {
    if (!dataQueue.IsAddingCompleted)
    {
    throw new TimeoutException();
    }
    }

    The idea is that if TryTake() returned false and CompleteAdding() has not been called yet, then it must have been a time-out. What we're seeing however is that sometimes TryTake() returns (almost) immediately (instead of waiting the timeout period) even though IsAddingCompleted is false. Is there a scenario where this is expected to happen? We noticed it at first in cases where timeout was set to Timeout.Infinite, in case it makes a difference.
    Regards,
    Theodor

     

    Wednesday, January 11, 2012 1:31 PM

Answers

  • Would need to see the rest of the code, TryTake() should only return false if no items to take arrived during the timeout period (or CompleteAdding()).  I've never seen that issue happen before, so would really need to see the code to see if some other side effect is going on.

    James Michael Hare

    Blog: http://www.geekswithblogs.net/BlackRabbitCoder

    Twitter: @BlkRabbitCoder

    There are 10 kinds of people in the world: those who know binary and those who don't...

    Wednesday, January 11, 2012 2:49 PM