有没有办法检查公共 MSMQ 是否为空?对于私有 MSMQ 来说很简单:
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;
}
我如何对公共 MSMQ 进行相同的检查?如果我尝试使用上面的代码检查公共 MSMQ,则会在 Peak 上出现错误:
System.ArgumentOutOfRangeException:长度不能小于零。
我刚刚开始使用消息队列,但我的同事有一个很好的方法来检查队列是否为空:
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
}
}
}
使用这种方法的好处是它不会抛出异常,而且我认为它不需要你等待超时发生。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)