问题
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