问题
I'm currently doing it like this:
MessageQueue queue = new MessageQueue(".\Private$\myqueue");
MessageEnumerator messageEnumerator = queue.GetMessageEnumerator2();
int i = 0;
while (messageEnumerator.MoveNext())
{
i++;
}
return i;
But for obvious reasons, it just feels wrong - I shouldn't have to iterate through every message just to get a count, should I?
Is there a better way?
回答1:
In C# the answer appears to be no - what you are doing is one of the only ways to do this and all the others are similar.
There are ways to do this using WMI or COM - have a look at the MSMQManagement com component. This has a MessageCount property.
I found the following post that may give you some other ideas for slightly better pure C # implementations:
Counting Messages in an MSMQ MessageQueue from C#
While the above appears to be all true, I should note that I've never tried to do this with MSMQ - I've only ever done standard reading from the queues.
回答2:
//here queue is msmq queue which you have to find count.
int index = 0;
MSMQManagement msmq = new MSMQManagement() ;
object machine = queue.MachineName;
object path = null;
object formate=queue.FormatName;
msmq.Init(ref machine, ref path,ref formate);
long count = msmq.MessageCount();
This is faster than you selected one. You get MSMQManagement class refferance inside "C:\Program Files (x86)\Microsoft SDKs\Windows" just browse in this address you will get it. for more details you can visit http://msdn.microsoft.com/en-us/library/ms711378%28VS.85%29.aspx.
回答3:
The best way to get the count from messageQueue is
MessageQueue queue = new MessageQueue(".\Private$\myqueue");
int iCount = queue.GetAllMessages().count();
来源:https://stackoverflow.com/questions/2619208/is-there-a-better-way-to-count-the-messages-in-an-message-queue-msmq