使用 .net“打开”MSMQ

Vac*_*ano 4 .net c# msmq

我有一个调用来获取失败的 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;
}
Run Code Online (Sandbox Code Playgroud)

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

此代码在设置相同(但不为空)的另一个队列上运行良好。

小智 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());
        }
    }
Run Code Online (Sandbox Code Playgroud)