Condividi tramite


How to count messages in a MessageQueue

There are a few different ways of getting a count of the number of messages in the MessageQueue. Here’s a simple one.

       public static int GetMessageCount(MessageQueue q)

       {

           int messageCount = 0;

           using (MessageEnumerator messageEnumerator = q.GetMessageEnumerator2())

           {

               while (messageEnumerator.MoveNext())

               {

                   messageCount++;

               }

           }

           return messageCount;

       }

The GetMessageEnumerator2 method creates a dynamic list of all the messages in that queue. So you can iterate over the list to get the count.

Other ways of doing this are:

  1. Peek the queue with a cursor
  2. COM Interop
  3. MSMQ Performance counters via WMI
  4. MSMQ Admin APIs