7

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?

Damovisa
  • 19,213
  • 14
  • 66
  • 88

3 Answers3

4

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.

David Hall
  • 32,624
  • 10
  • 90
  • 127
1
            //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.

Contango
  • 76,540
  • 58
  • 260
  • 305
rhatwar007
  • 343
  • 3
  • 14
-2

The best way to get the count from messageQueue is

MessageQueue queue = new MessageQueue(".\Private$\myqueue");
int iCount = queue.GetAllMessages().count();
thkala
  • 84,049
  • 23
  • 157
  • 201
Vinay S
  • 13
  • 1