如何:为检索到的消息指定格式化程序

更新:2007 年 11 月

必须指示从队列中检索消息时要使用的格式化程序对象。格式化程序指示从队列中移除消息时如何反序列化该消息。根据使用的格式化程序类型,可能需要设置附加的属性指定格式化程序应如何进行。

默认情况下,对大多数操作使用 XmlMessageFormatter。有关可使用的格式化程序的更多信息,请参见消息序列化。有关 XmlMessageFormatter 对象的唯一属性的信息,请参见读取和检索消息介绍

可以在代码或“属性”窗口中指定格式化程序。另外,还可以在队列或消息上设置格式化程序。当打算直接访问队列的消息时,在队列上设置格式化程序,如以下代码所示:

Console.WriteLine(CStr(MessageQueue1.Receive().Body))
     Console.WriteLine(MessageQueue1.Receive().Body.ToString());

当打算通过消息对象检索队列的内容时,在消息上设置格式化程序:

Message1 = MessageQueue1.Receive()
     message1 = messageQueue1.Receive();

在“属性”窗口中指定格式化程序

  1. 创建并配置 MessageQueue 组件实例。有关更多信息,请参见如何:创建 MessageQueue 组件实例

  2. 在设计器中,单击 MessageQueue 实例,然后访问“属性”窗口。

  3. Formatter 属性设置为适当的值。

  4. 如果选择了 XmlMessageFormatter 对象或 BinaryMessageFormatter 对象,请展开该属性,并设置所需的子属性以配置格式化程序。

以编程方式指定格式化程序

  1. 创建并配置 MessageQueue 组件实例。有关更多信息,请参见如何:创建 MessageQueue 组件实例

  2. 在“代码编辑器”中,创建类型为 XmlMessageFormatterActiveXMessageFormatterBinaryMessageFormatter 的格式化程序对象。

  3. 为格式化程序设置所需的任何属性。

  4. 检索消息。

    例如,下面的代码演示如何创建和配置一个使用 XmlMessageFormatter 对象从名为 MyQueue 的公共队列中检索消息的组件。

    Dim mq As New System.Messaging.MessageQueue(".\MyQueue")
    Dim formatter As System.Messaging.XmlMessageFormatter = _
       CType(mq.Formatter, System.Messaging.XmlMessageFormatter)
    formatter.TargetTypeNames = New String() {"System.String"}
    Dim m As System.Messaging.Message = mq.Receive(New TimeSpan(0, 0, 3))
    
         System.Messaging.MessageQueue mq =
               new System.Messaging.MessageQueue(".\\MyQueue");
            string[] types = { "System.String" };
            ((System.Messaging.XmlMessageFormatter)mq.Formatter).TargetTypeNames =
               types;
            System.Messaging.Message m = mq.Receive(new TimeSpan(0, 0, 3));
    
    

请参见

任务

如何:以编程方式接收消息

概念

读取和检索消息介绍