How to check if public MSMQ is empty

独自空忆成欢 提交于 2019-12-23 15:11:10

问题


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.


回答1:


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




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/3686312/how-to-check-if-public-msmq-is-empty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!