gpt4 book ai didi

c# - 检测 MSMQ 错误

转载 作者:行者123 更新时间:2023-11-30 17:41:33 27 4
gpt4 key购买 nike

我有以下代码(逐字),我希望它会产生错误:

using System.Messaging;

namespace MsmqTest
{
class Program
{
static void Main()
{
string invalidQueue = @"FormatName:DIRECT=OS:sometrahsname\private$\anothertrahsname";
Enqueue("test",invalidQueue);

}

private static void Enqueue(object o, string queueName)
{
using (MessageQueue msmq = new MessageQueue(queueName))
using (MessageQueueTransaction transaction = new MessageQueueTransaction())
{
msmq.DefaultPropertiesToSend.Recoverable = true;
transaction.Begin();
msmq.Send(new Message(o), transaction);
transaction.Commit();
}
}
}
}

这里我们向不存在的服务器上的队列发送消息。我希望收到出错的指示。我没有得到任何。在这种情况下如何检查错误?

注意:为了运行上面的代码,您需要在计算机上安装 MSMQ。

最佳答案

我之前在我的一个应用程序中偶然发现了这个问题。 MSDN 记录在 MessageQueue.Send 中,消息可能会被发送到死信队列而不会引发异常。这就是你现在正在经历的。我所做的是检查队列是否存在。

using System;
using System.Messaging;

namespace MsmqTest
{
class Program
{
static void Main(string[] args)
{
string invalidQueue = @"FormatName:DIRECT=OS:sometrahsname\private$\anothertrahsname";
Enqueue("test", invalidQueue);
}

private static void Enqueue(object o, string queueName)
{
try
{
MessageQueue msmq = null;
//check if queueName exists
//it also validates if you have access to MSMQ server
if (!MessageQueue.Exists(queueName))
{
msmq = MessageQueue.Create(queueName);

//you can also set the permission here
//because the other application that may be reading
//has different account with the application that created the queue
//set to Everyone for demonstration purposes
msmq.SetPermissions("Everyone", MessageQueueAccessRights.FullControl);
}
else
{
msmq = new MessageQueue(queueName);
}

using (msmq)
{
using (MessageQueueTransaction transaction = new MessageQueueTransaction())
{
msmq.DefaultPropertiesToSend.Recoverable = true;
transaction.Begin();
msmq.Send(new Message(o), transaction);
transaction.Commit();
}
}
}catch(Exception)
{
//handle error here
}
}
}
}

关于c# - 检测 MSMQ 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32815219/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com