To check how many messages are in a MSMQ Queue
MSMQ用遍历的方式得到消息队列中消息总数在消息总数巨大的时候效率很低下,推荐下面两种方法获取MSMQ队列中消息总数。
方法一:使用MSMQ Management Object,定义在Windows/System32下的mqoa.dll(Microsoft Message Queue 3.0 object library)
MSMQManagement _manager = new MSMQManagement();
_manager.Init("MACHINE", null, @"DIRECT=OS:MACHINE\PRIVATE$\sample");
Console.WriteLine(_manager.MessageCount);
Marshal.ReleaseComObject(_manager);
方法二:使用性能监视器
public int? CountQueue(MessageQueue queue, bool isPrivate)
{
int? Result = null;
try
{
//MSMQ.MSMQManagement mgmt = new MSMQ.MSMQManagement();
var mgmt = new MSMQ.MSMQManagementClass();
try
{
String host = queue.MachineName;
Object hostObject = (Object)host;
String pathName = (isPrivate) ? queue.FormatName : null;
Object pathNameObject = (Object)pathName;
String formatName = (isPrivate) ? null : queue.Path;
Object formatNameObject = (Object)formatName;
mgmt.Init(ref hostObject, ref formatNameObject, ref pathNameObject);
Result = mgmt.MessageCount;
}
finally
{
mgmt = null;
}
}
catch (Exception exc)
{
if (!exc.Message.Equals("Exception from HRESULT: 0xC00E0004", StringComparison.InvariantCultureIgnoreCase))
{
if (log.IsErrorEnabled) { log.Error("Error in CountQueue(). Queue was [" + queue.MachineName + "\\" + queue.QueueName + "]", exc); }
}
Result = null;
}
return Result;
}
参考材料:
MSMQManagement
http://stackoverflow.com/questions/3869022/is-there-a-way-to-check-how-many-messages-are-in-a-msmq-queue
http://stackoverflow.com/questions/8214308/msmqget-the-count-of-messages-from-msmq-queue-in-remote-machine
Direct Format Names
Message Queuing Object Libraries
还没有评论,来说两句吧...