MSMQ - 按路径获取特定队列

时间:2013-12-09 22:33:32

标签: c# msmq

我觉得奇怪的是,在MSMQ中有一种名为MessageQueue.ExistsMessageQueue.Create的方法。但是,没有方法可以在给定路径的情况下检索队列,即使提到的两个方法也将路径作为参数。

如何通过路径有效检索队列?

我能做到:

MessageQueue.GetPrivateQueuesByMachine(".").First(m => m.Path == "something");

但我不会称之为纯粹也不高效。我的机器将处理大量流动的队列消息,目前有多达250个队列在运行。

大多数这些队列都是从ASP .NET MVC站点处理的,我无法“存储”队列的引用以供以后使用。每个请求都需要再次获取每个队列。

2 个答案:

答案 0 :(得分:0)

如果队列不是动态创建的,我会玩下面的代码:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Messaging;
static class MessageQueueHelper
{
    private static Dictionary<string, MessageQueue> queues;
    public static MessageQueue GetPrivateQueueByName(string machinename, string queueName)
    {

        if (machinename == ".") {
            machinename = Environment.MachineName;
        }
        if (queues == null) {
            queues = new Dictionary<string, MessageQueue>();
            try {
                dynamic qlist = MessageQueue.GetPrivateQueuesByMachine(machinename).ToList;
                foreach (MessageQueue q in qlist) {
                    queues.Add(q.MachineName.ToLowerInvariant + q.Path.ToLowerInvariant, q);
                }
            } catch (Exception ex) {
                //access denied? server not found?
                throw new Exception(ex.Message);
            }
        }

        string key = string.Format("{0}FormatName:DIRECT=OS:{0}\\private$\\{1}", machinename, queueName).ToLowerInvariant;
        try {
            return queues.Item(key);
        } catch (Exception ex) {
            return null; //probably key not found
        }

    }


}

答案 1 :(得分:0)

使用MessageQueue constructor

MessageQueue mq = new MessageQueue(queuePath);
相关问题