3月21日
Counting messages in Queue - the .NET version
Some of you have noticed that my first blog - from December 7 - actually contains rather old code for counting messages in the queue. John had posted the following comment:
---- Quote ----
Hi Yoel,
Could you please give me a sample code to count the number of messages in a queue using C# and the .NET environment. I do have MSMQ 3.0 on my machine.
Thanks much,
John
---- End Qoute ----
Unfortunately, the current managed MSMQ APIs (System.Messaging) does not support the MSMQ admin APIs yet (not even in .NET 2.0). So, basically we have three options:
- Use the performance counters API to get the counters. The following code will do the trick:
using System.Diagnostics;
PerformanceCounterCategory myCat = new PerformanceCounterCategory("MSMQ Queue");
PerformanceCounter cntr = new PerformanceCounter();
cntr.CategoryName = "MSMQ Queue";
cntr.CounterName = "Messages in Queue";
foreach (string inst in myCat.GetInstanceNames())
{
cntr.InstanceName = inst;
Console.Write(inst + " = ");
Console.WriteLine(cntr.NextValue().ToString());
}
- Using COM interop and MSMQ object. The following code will do it, after adding a reference to Microsoft Message Queue 3.0 object library:
using System.Windows.Forms; // for SystemInformation
object oMissing = Type.Missing;
object oMachine = SystemInformation.ComputerName;
MSMQ.MSMQApplicationClass msmqApp =
new MSMQ.MSMQApplicationClass();
foreach (object oFormat in (object[])msmqApp.ActiveQueues)
{
MSMQ.MSMQManagementClass qMgmt = new MSMQ.MSMQManagementClass();
object oFormatName = oFormat; // oFormat is read only and we need to use ref
qMgmt.Init(ref oMachine, ref oMissing, ref oFormatName);
Console.WriteLine(oFormatName.ToString() + " = " + qMgmt.MessageCount.ToString());
}
This method is more reliable than performance counters, but works on MSMQ 3.0 only.
- Calling MQMgmtGetInfo directly to get the active queues (PROPID_MGMT_MSMQ_ACTIVEQUEUES) if needed, and to get the number of messages in each queue (PROPID_MGMT_QUEUE_BYTES_IN_QUEUE). Marshaling the parameters to this call (especially the third one, MQMGMTPROPS structure may be a little tricky, so I was too lazy to write a sample this time
.
I may try putting up a sample when I have some extra time, however this is also an interesting challenge to the readers. Any taker? I promise to post the solution in my blog with all the credit.
The advantage of this method is that it is as reliable as COM interop (method 2), but faster. Unlike COM interop, it will work with all the versions of MSMQ.
On other issues: I know I promised putting up a comparison chart for MSMQ Explorers. I also got a mail from James Willock from mulhollandsoftware.com, announcing the 2nd beta of QSet, with new cool features (and some bugs, too - well, this is how beta is supposed to be
). Don't you feel sometimes that your todo list gets longer as your time gets shorter? I will try to post it for you soon, though...
See you,
Yoel