Search code examples
c#msmqnetmsmqbinding

How to check if public MSMQ is empty


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.


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