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

Justin picture Justin · Oct 6, 2010 · Viewed 37.9k times · Source

I was wondering if there is a way to programmatically check how many messages are in a private or public MSMQ using C#? I have code that checks if a queue is empty or not using the peek method wrapped in a try/catch, but I've never seen anything about showing the number of messages in the queue. This would be very helpful for monitoring if a queue is getting backed up.

Answer

Gary Wright picture Gary Wright · Oct 30, 2012

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());