C# MSMQ Invalid Operation Exception

会有一股神秘感。 提交于 2019-12-25 08:58:53

问题


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);
     }
}

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


回答1:


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.



来源:https://stackoverflow.com/questions/28875912/c-sharp-msmq-invalid-operation-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!