本文介绍了C#MSMQ无效操作异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个基本应用程序来管理C#中的MSMQ.

I create a basic application to manage MSMQ in C#.

我使用以下方法在交易消息队列中创建消息:

I create messages in my trasaction message queue with this method:

/// <summary>
/// Method to send message in message queue
/// </summary>
/// <param name="mq">message queue (to)</param>
/// <param name="messageBody">message body</param>
/// <param name="messageLabel">message label</param>
public static void sendMessage(MessageQueue mq, string messageBody, string messageLabel)
{
      MessageQueueTransaction mqt = new MessageQueueTransaction();
      try
      {
            Message m = new Message(messageBody, new XmlMessageFormatter(new String[] { "System.String,mscorlib" }));
            m.BodyType = 0;
            mqt.Begin();
            mq.Send(m, messageLabel, mqt);
            mqt.Commit();
       }
       catch (Exception ex)
       {
            string s = ex.Message;
            mqt.Abort();
       }
       finally
       {
            mq.Close();
       }
}

对于消息处理(在控制台中写内容消息),我使用以下方法:

For the message treatment (write content message in console), I use this:

/// <summary>
/// Get all messages in MSMQ
/// </summary>
/// <param name="mq"> MSMQ </param>
public static void getMessage(MessageQueue mq)
{
     Message[] messages = mq.GetAllMessages();
     try
     {
           foreach (Message m in messages)
           {

                Console.WriteLine("Message" + m.Label = ": " + m.Body.ToString());
           }
     }
     catch (Exception ex)
     {

            Console.WriteLine(ex.Message);
     }
}

所有消息都在messages数组中,但是我在foreach语句的一行中有一个Invalid Operation Exception.当我使用调试器时,我可以看到很多message属性都有异常.我只想确保我在邮件中发送标签和正文以备以后使用.send或get方法是否有错误(或两者都有)? -谢谢

All messages are in the messages array but I have a Invalid Operation Exception in the line in the foreach statement.When I use the debugger, I can see lot of message property have an exception.I just want to be sure I send label and body in my message to get it later.Is the send or the get method who have an error (or the both) ? --Thank you

推荐答案

问题是您在发送时正在应用自定义消息格式化程序,但在接收时却没有.如果进一步研究该异常,您可能会在内部异常中看到更多详细信息,例如:找不到能够读取此消息的格式化程序."

Problem is you're applying custom message formatter when sending, but not when receiving. If you investigated that exception a bit further you would probably see more details in inner exception, something like: "Cannot find a formatter capable of reading this message."

修复很简单.只需在接收队列上设置相同的格式化程序即可:

Fix is simple. Just set that same formatter on receiving queue as well:

queue.Formatter = new XmlMessageFormatter( new String[] {"System.String,mscorlib"} );

此外,您也可以将其用于发送队列.如果您发送多条消息,则最好始终在队列中指定一次,而不要为每条消息分别指定(如果始终相同).

Also, you can use this for sending queue as well. If you send multiple messages it's better to specify it once on the queue instead for each message separately if it's always the same.

这篇关于C#MSMQ无效操作异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 22:19