Is there a way to check how many messages are in a MSMQ Queue?

If you need a fast method (25k calls/second on my box), I recommend Ayende's version based on MQMgmtGetInfo() and PROPID_MGMT_QUEUE_MESSAGE_COUNT:

for C# https://github.com/hibernating-rhinos/rhino-esb/blob/master/Rhino.ServiceBus/Msmq/MsmqExtensions.cs

for VB https://gist.github.com/Lercher/5e1af6a2ba193b38be29

The origin was probably http://functionalflow.co.uk/blog/2008/08/27/counting-the-number-of-messages-in-a-message-queue-in/ but I'm not convinced that this implementation from 2008 works any more.


You can read the Performance Counter value for the queue directly from .NET:

using System.Diagnostics;

// ...
var queueCounter = new PerformanceCounter(
    "MSMQ Queue", 
    "Messages in Queue", 
    @"machinename\private$\testqueue2");

Console.WriteLine( "Queue contains {0} messages", 
    queueCounter.NextValue().ToString());

There is no API available, but you can use GetMessageEnumerator2 which is fast enough. Sample:

MessageQueue q = new MessageQueue(...);
int count = q.Count();

Implementation

public static class MsmqEx
{
    public static int Count(this MessageQueue queue)
    {
        int count = 0;
        var enumerator = queue.GetMessageEnumerator2();
        while (enumerator.MoveNext())
            count++;

        return count;
    }
}

I also tried other options, but each has some downsides

  1. Performance counter may throw exception "Instance '...' does not exist in the specified Category."
  2. Reading all messages and then taking count is really slow, it also removes the messages from queue
  3. There seems to be a problem with Peek method which throws an exception

Tags:

C#

Msmq