4

我有一个电话来获取失败的 MSMQ 的计数。

经过一番研究,我发现了这个问题:Reading MSMQ message count with ruby

那里的答案表明,如果队列为空且已关闭,则您无法获得“性能指标”(包括消息计数)。

所以我现在的问题是,如何使用.NET 和C# 以编程方式“打开”(即“取消关闭”)MSMQ?


更新:如果它是相关的,这是我获取消息计数的代码:

private static int GetMessageCount(string queueName, string machine)
{
    MSMQManagement queue = new MSMQManagement();

    string formatName = @"DIRECT=OS:" + machine + @"\PRIVATE$\" + queueName;
    queue.Init(machine, null, formatName);
    return queue.MessageCount;
}

错误发生在queue.Init。错误消息是:“队列未打开或可能不存在。”

此代码在另一个设置相同(但不为空)的队列上工作得很好。

4

2 回答 2

5

要解决“队列未打开”错误,您可以使用标准 msmq 调用打开队列,并在稍稍超时的情况下查看消息。您必须捕获超时异常“请求的操作的超时已过期”。但在超时后,您可以使用 MSMQManagement 对象查询队列,即使它有 0 条消息:

        MSMQ.MSMQApplication q = new MSMQ.MSMQApplication();
        object obj = q.ActiveQueues;
        foreach (object oFormat in (object[])q.ActiveQueues)
        {
            object oMissing = Type.Missing;
            object oMachine = System.Environment.MachineName;
            MSMQ.MSMQManagement qMgmt = new MSMQ.MSMQManagement();
            object oFormatName = oFormat; // oFormat is read only and we need to use ref
            qMgmt.Init(ref oMachine, ref oMissing, ref oFormatName);
            outPlace.Text += string.Format("{0} has {1} messages queued \n", oFormatName.ToString(), qMgmt.MessageCount.ToString());
        }
        foreach (object oFormat in (object[])q.PrivateQueues)
        {
            object oMissing = Type.Missing;
            object oMachine = System.Environment.MachineName;
            MSMQ.MSMQManagement qMgmt = new MSMQ.MSMQManagement();
            queue = new MessageQueue(oFormat.ToString());
            object oFormatName = queue.FormatName; // oFormat is read only and we need to use ref
            TimeSpan timeout=new TimeSpan(2);
           try
           {
                Message msg = queue.Peek(timeout);
            }
            catch
            {// being lazy and catching everything for this example
            }
            qMgmt.Init(ref oMachine, ref oMissing, ref oFormatName);
              outPlace.Text += string.Format("{0}  {1} {2}\n", oFormat.ToString(), queue.FormatName.ToString(), qMgmt.MessageCount.ToString());
        }
    }
于 2014-05-14T19:25:53.570 回答
0

获取队列中消息数量的另一种方法可能是使用 MessageQueue 类的 GetAllMessages 方法。它返回一个 Message[] ,它是队列中所有消息的静态快照。之后,您可以读取 Length 参数以获取消息数。

这是 msdn 链接:http: //msdn.microsoft.com/en-gb/library/system.messaging.messagequeue.getallmessages.aspx

于 2013-04-17T14:05:24.053 回答