Question

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.

Was it helpful?

Solution

The Peek method is only available on remote machines when you use a direct format name to access the queue. You should be able to use the same code, so long as you're not relying on directory services to get you to the queue.

Direct queue names generally look something like: DIRECT=URLAddressSpecification/QueueName

OTHER TIPS

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.

Leo, you sure about that? You can't use a path name with a remote Peek? The error returned doesn't say invalid format name, which would be expected if that was the case. In fact the error appears to be on the "isQueueEmpty = false" line - the try/catch doesn't differentiate between the peek and the isQueueEmpty lines. I bet the isQueueEmpty call is receiving an exception which translates to an negative number. Now your solution, though, may be correct - a lot of remote calls in MSMQ require format names instead of path names. So if you use a format name for creating myQueue, the isQueueEmpty should work.

Cheers

John Breakwell

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top