System.InvalidOperationException: 指定类别中不存在实例“[私有队列路径]”

System.InvalidOperationException: Instance '[private Queue path]' does not exist in the specified Category

我正在使用以下代码获取消息队列计数,此方法每 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;
            }

问题是下面的异常有时是thrown:and当消息队列计数基本上为新创建的队列时变为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)
------

我认为这是因为性能计数器尚不存在(对于从未有过任何消息的新队列)或已被删除。由于无论如何都要实例化 MessageQueue 对象,因此获取计数的更可靠方法可能是调用 messageQueue.GetAllMessages().Length。只要您没有在 MessageQueuePropertyFilter 中启用 Body 属性,它就不会非常昂贵。