MSMQ - Get specific queue by path

依然范特西╮ 提交于 2019-12-11 19:04:08

问题


I find it strange that in MSMQ there's a method called MessageQueue.Exists and MessageQueue.Create. However, there's no method for retrieving a queue given its path, even though the two mentioned methods take a path as an argument.

How can I retrieve a queue efficiently by its path?

I could do:

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

But I wouldn't call that pure nor efficient. My machine will handle large quantities of queue messages flowing around, with as much as 250 queues running currently.

Most of these queues are being handled from an ASP .NET MVC site, where I can't "store" a queue's reference for later use. Every queue will need to be fetched again for every request.


回答1:


if the queues are not created dynamically, I would play around the following code:

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
        }

    }


}



回答2:


Use the MessageQueue constructor

MessageQueue mq = new MessageQueue(queuePath);


来源:https://stackoverflow.com/questions/20482254/msmq-get-specific-queue-by-path

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!