我正在使用以下代码来获取消息队列计数时间从此方法每隔15秒调用一次
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;
}
问题是有时抛出以下异常:当消息队列计数基本上为新创建的队列变为0时抛出此异常
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)
------
答案 0 :(得分:0)
我认为这是因为性能计数器要么尚未存在(对于从未有任何消息的新队列),要么被删除。由于您无论如何都要实例化MessageQueue对象,因此获得计数的更可靠方法可能是调用messageQueue.GetAllMessages().Length
。只要您没有在MessageQueuePropertyFilter中启用Body属性,它就不会非常昂贵。