"Open" a MSMQ with .net
本文关键字:quot net with Open MSMQ | 更新日期: 2023-09-27 17:50:31
我有一个调用来获取失败的MSMQ的计数。
经过一番研究,我发现了这个问题:使用ruby读取MSMQ消息计数
那里的答案表明,如果队列为空并且关闭,则无法获得"性能指标"(包括消息计数)。
所以我现在的问题是,我如何以编程方式"打开"(即"取消关闭")一个MSMQ使用。net和c# ?
更新:如果它是相关的,这里是我的代码来获取消息计数:
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;
}
queue.Init
出错。错误消息是:"队列未打开或可能不存在。"
这段代码在另一个设置相同的队列(但不是空的)上工作得很好。
要绕过"queue is not open"错误,您可以通过使用标准的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());
}
}
获取队列中消息数的另一种方法可能是使用MessageQueue类的GetAllMessages方法。它返回一个Message[],它是队列中所有消息的静态快照。之后,您可以读取Length参数以获得消息的数量。
这里是msdn链接:http://msdn.microsoft.com/en-gb/library/system.messaging.messagequeue.getallmessages.aspx