I am using following code to get message Queue count time to time from this method is calling on every 15s
public JObject GetQueueItemsCount()
{
JObject returnObject = new JObject();
int queueCount = 0;
var queueName = @"" + ConfigurationManager.AppSettings["QueueName"];
try
{
MessageQueue messageQueue = new MessageQueue(queueName);
if (MessageQueue.Exists(queueName))
{
var queueCounter = new PerformanceCounter("MSMQ Queue", "Messages in Queue", queueName, @"" + ConfigurationManager.AppSettings["MachineName"]);
queueCount = (int)queueCounter.NextValue();
}
}
catch (Exception ex)
{
throw ex;
}
finally {
returnObject.Add("queueCount", queueCount);
}
return returnObject;
}
The problem is that following Exception is sometimes thrown:and this exception throws when the message queue count become 0 basically for a newly created queue
System.InvalidOperationException: Instance 'xxxxx\private$\xxx_queue' does not exist in the specified Category.
at xxxxx.BusinessObjects.ControllerRepositories.xxxxRepository.GetQueueItemsCount()
at lambda_method(Closure , Object , Object[] )
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)
------
I believe this is because the Performance Counter either doesn't exist yet (for a new queue that has never had any messages), or was removed. Since you're instantiating the MessageQueue object anyway, a more reliable way to get the count may be to call messageQueue.GetAllMessages().Length
. As long as you don't have the Body property enabled in your MessageQueuePropertyFilter, it shouldn't be extremely expensive.