如何取得消息队列中消息总数

.NET MessageQueue 类没有取得消息队列中消息总数的API,用遍历的方式得到消息队列中消息总数在消息总数巨大的时候效率很低下,以下办法可以比较好的解决这个问题。

1. 运行环境。

Windows 2003 Server

VS2005

安装消息队列服务

2. 添加引用。

如下图在项目中添加引用。

clip_image002 

3. 方法

        /// <summary>
       
/// 得到消息队列中消息个数
       
/// </summary>
       
/// <param name="machineName">消息队列机器名</param>
       
/// <param name="queueFormatName">消息队列FormatName</param>
       
/// <returns>消息队列中消息总数</returns>

        private int GetMessageCount(string machineName, string queueFormatName)
       
{
            MSMQ.MSMQManagement mgmt
= new MSMQ.MSMQManagement();
            Object ss
= (Object)machineName;
            Object pn
= (Object)queueFormatName;
            Object f
= (Object)null;
            mgmt.Init(
ref ss, ref f, ref pn);
           
return mgmt.MessageCount;
        }

4. 调用

int msgCount = GetMessageCount(msgQueue.MachineName, msgQueue.FormatName);

msgQueue---内聚的MessageQueue对象

5. 限制

该方法适用于消息队列服务与应用程序都在一台电脑上时适用,二者不在一台电脑上时会抛出异常,具体原因不明。

6. 参考资料

MSDN 搜索 MSMQManagement。

posted @ 2009-06-06 09:43  地之雾  阅读(3080)  评论(1编辑  收藏  举报