我编写了这段代码,但它让我开始思考应该如何使用 MSMQ:我应该使用“使用”语句来获取消息队列吗?Using 语句将在我完成队列时处理它,但我什么时候完成它?我应该保存我的 MessageQueue 对象以供重用。假设这是在 ASP.Net 应用程序中,我想从同一个操作将 3 条消息发送到同一个队列。像我现在一样保存对象并重用或创建和处置?
using (MessageQueue msgQueue = new MessageQueue(this.queueName))
{
using (MessageQueueTransaction msgTx = new MessageQueueTransaction())
{
Message recoverableMessage = null;
msgTx.Begin();
try
{
recoverableMessage = new Message();
recoverableMessage.Body = message;
recoverableMessage.Formatter = new BinaryMessageFormatter(System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple, System.Runtime.Serialization.Formatters.FormatterTypeStyle.TypesAlways);
recoverableMessage.Recoverable = true;
msgQueue.Send(recoverableMessage, msgTx);
////this.msgQ.Send(recoverableMessage, msgTx); //whats up here??? this will teach me for taking time off. not sure whuc I shuold use
msgTx.Commit();
result = recoverableMessage.Id;
//recoverableMessage.Dispose();
}
catch (Exception)
{
msgTx.Abort();
////recoverableMessage.Dispose();
}
finally
{
if (recoverableMessage != null)
{
recoverableMessage.Dispose();
}
}
}
}