How to check if public MSMQ is empty

Justin picture Justin · Sep 10, 2010 · Viewed 7.2k times · Source

Is there any way to check if a public MSMQ is empty? For a private MSMQ it's easy:

private bool IsQueueEmpty(string path)
        {
            bool isQueueEmpty = false;
            var myQueue = new MessageQueue(path);
            try
            {
                myQueue.Peek(new TimeSpan(0));
                isQueueEmpty = false;
            }
            catch (MessageQueueException e)
            {
                if (e.MessageQueueErrorCode == MessageQueueErrorCode.IOTimeout)
                {
                    isQueueEmpty = true;
                }
            }
            return isQueueEmpty;
        }

How would I do the same check for a public MSMQ? If I try to check a public MSMQ with the code above it gives me an error on the Peak:

System.ArgumentOutOfRangeException: Length cannot be less than zero.

Answer

John B picture John B · Dec 29, 2011

I just started working with Message Queues but my coworker has this nice way for checking if a queue is empty:

if (MessageQueue.Exists(fullQueuePath))
{
    // FYI, GetMessageQueue() is a helper method we use to consolidate the code
    using (var messageQueue = GetMessageQueue(fullQueuePath))
    {
        var queueEnum = messageQueue.GetMessageEnumerator2();

        if (queueEnum.MoveNext())
        {
            // Queue not empty
        }
        else
        {
            // Queue empty
        }
    }
}

The benefit of using this method is that it doesn't throw an exception, and I don't think it requires you to wait for a timeout to occur.