Why doesn't ConcurrentQueue<T>.Count return 0 when IsEmpty == true?

Posted by DanTup - Danny Tuppeny on Stack Overflow See other posts from Stack Overflow or by DanTup - Danny Tuppeny
Published on 2011-02-27T11:51:58Z Indexed on 2011/02/27 15:25 UTC
Read the original article Hit count: 262

Filed under:
|
|

I was reading about the new concurrent collection classes in .NET 4 on James Michael Hare's blog, and the page talking about ConcurrentQueue<T> says:

It’s still recommended, however, that for empty checks you call IsEmpty instead of comparing Count to zero.

I'm curious - if there is a reason to use IsEmpty instead of comparing Count to 0, why does the class not internally check IsEmpty and return 0 before doing any of the expensive work to count?

E.g.:

public int Count
{
    get
    {
        // Check IsEmpty so we can bail out quicker
        if (this.IsEmpty)
            return 0;

        // Rest of "expensive" counting code
    }
}

It seems strange to suggest this if it could be "fixed" so easily with no side-effects?

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET