通过


Message 类

定义

提供对定义消息队列消息所需的属性的访问权限。

public ref class Message : System::ComponentModel::Component
public class Message : System.ComponentModel.Component
type Message = class
    inherit Component
Public Class Message
Inherits Component
继承

示例

下面的代码示例演示如何使用 BinaryMessageFormatter.

using System;
using System.Messaging;
using System.Drawing;
using System.IO;

namespace MyProject
{

    /// <summary>
    /// Provides a container class for the example.
    /// </summary>
    public class MyNewQueue
    {

        //**************************************************
        // Provides an entry point into the application.
        //		
        // This example sends and receives a message from
        // a queue.
        //**************************************************

        public static void Main()
        {
            // Create a new instance of the class.
            MyNewQueue myNewQueue = new MyNewQueue();

            // Create a queue on the local computer.
            CreateQueue(".\\myQueue");
            
            // Send a message to a queue.
            myNewQueue.SendMessage();

            // Receive a message from a queue.
            myNewQueue.ReceiveMessage();

            return;
        }

        //**************************************************
        // Creates a new queue.
        //**************************************************

        public static void CreateQueue(string queuePath)
        {
            try	
            {
                if(!MessageQueue.Exists(queuePath))
                {
                    MessageQueue.Create(queuePath);
                }
                else
                {
                    Console.WriteLine(queuePath + " already exists.");
                }
            }
            catch (MessageQueueException e)
            {
                Console.WriteLine(e.Message);
            }
        }

        //**************************************************
        // Sends an image to a queue, using the BinaryMessageFormatter.
        //**************************************************
        
        public void SendMessage()
        {
            try{

                // Create a new bitmap.
                // The file must be in the \bin\debug or \bin\retail folder, or
                // you must give a full path to its location.
                Image myImage = Bitmap.FromFile("SentImage.bmp");

                // Connect to a queue on the local computer.
                MessageQueue myQueue = new MessageQueue(".\\myQueue");
                
                Message myMessage = new Message(myImage, new BinaryMessageFormatter());

                // Send the image to the queue.
                myQueue.Send(myMessage);
            }
            catch(ArgumentException e)
            {
                Console.WriteLine(e.Message);
            }

            return;
        }

        //**************************************************
        // Receives a message containing an image.
        //**************************************************
        
        public  void ReceiveMessage()
        {
                        
            try
            {

                // Connect to the a queue on the local computer.
                MessageQueue myQueue = new MessageQueue(".\\myQueue");

                // Set the formatter to indicate body contains an Order.
                myQueue.Formatter = new BinaryMessageFormatter();

                // Receive and format the message.
                System.Messaging.Message myMessage = myQueue.Receive();
                Bitmap myImage = (Bitmap)myMessage.Body;
                
                // This will be saved in the \bin\debug or \bin\retail folder.
                myImage.Save("ReceivedImage.bmp",System.Drawing.Imaging.ImageFormat.Bmp);
            }
            
            catch (MessageQueueException)
            {
                // Handle Message Queuing exceptions.
            }

            // Handle invalid serialization format.
            catch (InvalidOperationException e)
            {
                Console.WriteLine(e.Message);
            }

            catch (IOException e)
            {
                // Handle file access exceptions.
            }
            
            // Catch other exceptions as necessary.

            return;
        }
    }
}
Imports System.Messaging
Imports System.Drawing
Imports System.IO


Namespace MyProj
    _
   
   
   Public Class MyNewQueue
      
      
      '**************************************************
      ' Provides an entry point into the application.
      '		 
      ' This example sends and receives a message from
      ' a queue.
      '**************************************************
      Public Shared Sub Main()
         ' Create a new instance of the class.
         Dim myNewQueue As New MyNewQueue()
         
         ' Create a queue on the local computer.
         CreateQueue(".\myQueue")
         
         ' Send a message to a queue.
         myNewQueue.SendMessage()
         
         ' Receive a message from a queue.
         myNewQueue.ReceiveMessage()
         
         Return
      End Sub
      
      
      '**************************************************
      ' Creates a new queue.
      '**************************************************
      Public Shared Sub CreateQueue(queuePath As String)
         Try
            If Not MessageQueue.Exists(queuePath) Then
               MessageQueue.Create(queuePath)
            Else
               Console.WriteLine((queuePath + " already exists."))
            End If
         Catch e As MessageQueueException
            Console.WriteLine(e.Message)
         End Try
      End Sub
       
      
      '**************************************************
      ' Sends an image to a queue, using the BinaryMessageFormatter.
      '**************************************************
      Public Sub SendMessage()
         Try
            
            ' Create a new bitmap.
            ' The file must be in the \bin\debug or \bin\retail folder, or
            ' you must give a full path to its location.
            Dim myImage As Image = Bitmap.FromFile("SentImage.bmp")
            
            ' Connect to a queue on the local computer.
            Dim myQueue As New MessageQueue(".\myQueue")
            
            Dim myMessage As New Message(myImage, New BinaryMessageFormatter())
            
            ' Send the image to the queue.
            myQueue.Send(myMessage)
         Catch e As ArgumentException
            Console.WriteLine(e.Message)
         End Try 
         
         Return
      End Sub
      
      
      
      '**************************************************
      ' Receives a message containing an image.
      '**************************************************
      Public Sub ReceiveMessage()
         
         Try
            
            ' Connect to the a queue on the local computer.
            Dim myQueue As New MessageQueue(".\myQueue")
            
            ' Set the formatter to indicate body contains an Order.
            myQueue.Formatter = New BinaryMessageFormatter()
            
            ' Receive and format the message. 
            Dim myMessage As System.Messaging.Message = myQueue.Receive()
            Dim myImage As Bitmap = CType(myMessage.Body, Bitmap)
            
            ' This will be saved in the \bin\debug or \bin\retail folder.
            myImage.Save("ReceivedImage.bmp", System.Drawing.Imaging.ImageFormat.Bmp)
         
         
         
         'Catch
         ' Handle Message Queuing exceptions.
         
         ' Handle invalid serialization format.
         Catch e As InvalidOperationException
            Console.WriteLine(e.Message)
         
         Catch e As IOException
         End Try
         ' Handle file access exceptions.
         
         ' Catch other exceptions as necessary.
         Return
      End Sub
   End Class
End Namespace 'MyProj

下面的代码示例演示如何使用 XmlMessageFormatter.

#using <system.dll>
#using <system.messaging.dll>
#using <system.drawing.dll>

using namespace System;
using namespace System::Messaging;
using namespace System::Drawing;
using namespace System::IO;
ref class Order
{
public:
   int orderId;
   DateTime orderTime;
};

ref class MyNewQueue
{
public:
   static void CreateQueue( String^ queuePath )
   {
      try
      {
         if (  !MessageQueue::Exists( queuePath ) )
         {
            MessageQueue::Create( queuePath );
         }
         else
         {
            Console::WriteLine(  "{0} already exists.", queuePath );
         }
      }
      catch ( MessageQueueException^ e ) 
      {
         Console::WriteLine( e->Message );
      }

   }

   void SendMessage()
   {
      try
      {
         // Create a new order and set values.
         Order^ sentOrder = gcnew Order;
         sentOrder->orderId = 3;
         sentOrder->orderTime = DateTime::Now;

         // Connect to a queue on the local computer.
         MessageQueue^ myQueue = gcnew MessageQueue( ".\\myQueue" );

         // Create the new order.
         Message^ myMessage = gcnew Message( sentOrder );

         // Send the order to the queue.
         myQueue->Send( myMessage );
      }
      catch ( ArgumentException^ e ) 
      {
         Console::WriteLine( e->Message );
      }

      return;
   }

   void ReceiveMessage()
   {
      // Connect to the a queue on the local computer.
      MessageQueue^ myQueue = gcnew MessageQueue( ".\\myQueue" );

      // Set the formatter to indicate body contains an Order.
      array<Type^>^p = gcnew array<Type^>(1);
      p[ 0 ] = Order::typeid;
      myQueue->Formatter = gcnew XmlMessageFormatter( p );
      try
      {
         // Receive and format the message. 
         Message^ myMessage = myQueue->Receive();
         Order^ myOrder = dynamic_cast<Order^>(myMessage->Body);

         // Display message information.
         Console::WriteLine( "Order ID: {0}", myOrder->orderId );
         Console::WriteLine( "Sent: {0}", myOrder->orderTime );
      }
      catch ( MessageQueueException^ ) 
      {
         // Handle Message Queuing exceptions.
      }
      // Handle invalid serialization format.
      catch ( InvalidOperationException^ e ) 
      {
         Console::WriteLine( e->Message );
      }

      // Catch other exceptions as necessary.
      return;
   }
};

int main()
{
   // Create a new instance of the class.
   MyNewQueue^ myNewQueue = gcnew MyNewQueue;

   // Create a queue on the local computer.
   MyNewQueue::CreateQueue( ".\\myQueue" );

   // Send a message to a queue.
   myNewQueue->SendMessage();

   // Receive a message from a queue.
   myNewQueue->ReceiveMessage();
   return 0;
}
using System;
using System.Messaging;
using System.Drawing;
using System.IO;

namespace MyProject
{

    // The following example
    // sends to a queue and receives from a queue.
    public class Order
    {
        public int orderId;
        public DateTime orderTime;
    };	

    /// <summary>
    /// Provides a container class for the example.
    /// </summary>
    public class MyNewQueue
    {

        //**************************************************
        // Provides an entry point into the application.
        //		
        // This example sends and receives a message from
        // a queue.
        //**************************************************

        public static void Main()
        {
            // Create a new instance of the class.
            MyNewQueue myNewQueue = new MyNewQueue();

            // Create a queue on the local computer.
            CreateQueue(".\\myQueue");
            
            // Send a message to a queue.
            myNewQueue.SendMessage();

            // Receive a message from a queue.
            myNewQueue.ReceiveMessage();

            return;
        }

        //**************************************************
        // Creates a new queue.
        //**************************************************

        public static void CreateQueue(string queuePath)
        {
            try	
            {
                if(!MessageQueue.Exists(queuePath))
                {
                    MessageQueue.Create(queuePath);
                }
                else
                {
                    Console.WriteLine(queuePath + " already exists.");
                }
            }
            catch (MessageQueueException e)
            {
                Console.WriteLine(e.Message);
            }
        }

        //**************************************************
        // Sends an Order to a queue.
        //**************************************************
        
        public void SendMessage()
        {
            try
            {

                // Create a new order and set values.
                Order sentOrder = new Order();
                sentOrder.orderId = 3;
                sentOrder.orderTime = DateTime.Now;

                // Connect to a queue on the local computer.
                MessageQueue myQueue = new MessageQueue(".\\myQueue");

                // Create the new order.
                Message myMessage = new Message(sentOrder);

                // Send the order to the queue.
                myQueue.Send(myMessage);
            }
            catch(ArgumentException e)
            {
                Console.WriteLine(e.Message);
            }

            return;
        }

        //**************************************************
        // Receives a message containing an order.
        //**************************************************
        
        public  void ReceiveMessage()
        {
            // Connect to the a queue on the local computer.
            MessageQueue myQueue = new MessageQueue(".\\myQueue");

            // Set the formatter to indicate body contains an Order.
            myQueue.Formatter = new XmlMessageFormatter(new Type[]
                {typeof(MyProject.Order)});
            
            try
            {
                // Receive and format the message.
                Message myMessage =	myQueue.Receive();
                Order myOrder = (Order)myMessage.Body;

                // Display message information.
                Console.WriteLine("Order ID: " +
                    myOrder.orderId.ToString());
                Console.WriteLine("Sent: " +
                    myOrder.orderTime.ToString());
            }
            
            catch (MessageQueueException)
            {
                // Handle Message Queuing exceptions.
            }

                // Handle invalid serialization format.
            catch (InvalidOperationException e)
            {
                Console.WriteLine(e.Message);
            }
            
            // Catch other exceptions as necessary.

            return;
        }
    }
}
Imports System.Messaging
Imports System.Drawing
Imports System.IO



   
' The following example 
' sends to a queue and receives from a queue.
Public Class Order
      Public orderId As Integer
      Public orderTime As DateTime
End Class

   
  
' Provides a container class for the example.

Public Class MyNewQueue
      
      

   ' Provides an entry point into the application.
   '		 
   ' This example sends and receives a message from
   ' a queue.

   Public Shared Sub Main()
      ' Create a new instance of the class.
      Dim myNewQueue As New MyNewQueue()
        
      ' Create a queue on the local computer.
      CreateQueue(".\myQueue")
         
      ' Send a message to a queue.
      myNewQueue.SendMessage()
       
      ' Receive a message from a queue.
      myNewQueue.ReceiveMessage()
         
      Return
   End Sub
      
      

      ' Creates a new queue.
   Public Shared Sub CreateQueue(queuePath As String)
      Try
         If Not MessageQueue.Exists(queuePath) Then
            MessageQueue.Create(queuePath)
         Else
            Console.WriteLine((queuePath + " already exists."))
         End If
      Catch e As MessageQueueException
         Console.WriteLine(e.Message)
      End Try
   End Sub
       
      

      ' Sends an Order to a queue.

   Public Sub SendMessage()
      Try
            
            ' Create a new order and set values.
            Dim sentOrder As New Order()
            sentOrder.orderId = 3
            sentOrder.orderTime = DateTime.Now
            
            ' Connect to a queue on the local computer.
            Dim myQueue As New MessageQueue(".\myQueue")
            
            
            
            ' Create the new order.
            Dim myMessage As New Message(sentOrder)
            
            ' Send the order to the queue.
            myQueue.Send(myMessage)
      Catch e As ArgumentException
            Console.WriteLine(e.Message)
      End Try 
         
      Return
   End Sub
      
      
      
 
      ' Receives a message containing an order.
 
   Public Sub ReceiveMessage()
         ' Connect to the a queue on the local computer.
         Dim myQueue As New MessageQueue(".\myQueue")
         
         ' Set the formatter to indicate body contains an Order.
         myQueue.Formatter = New XmlMessageFormatter(New Type() {GetType(Order)})
         
         Try
            ' Receive and format the message. 
            Dim myMessage As Message = myQueue.Receive()
            Dim myOrder As Order = CType(myMessage.Body, Order)
            
            ' Display message information.
            Console.WriteLine(("Order ID: " + myOrder.orderId.ToString()))
            Console.WriteLine(("Sent: " + myOrder.orderTime.ToString()))
         
  
         ' Handle invalid serialization format.
         Catch e As InvalidOperationException
            Console.WriteLine(e.Message)
         End Try
         
         ' Catch other exceptions as necessary.
         Return
   End Sub
End Class

注解

使用 Message 类从队列中查看或接收消息,或在将消息发送到队列时对消息属性进行精细控制。

MessageQueue Message在从队列中查看或接收消息时使用该类,因为MessageQueue.Peek该类和MessageQueue.Receive方法都创建了该类的新实例Message并设置实例的属性。 类 Message 的只读属性适用于从队列检索消息,而读/写属性适用于发送和接收消息。 从队列中查看或接收消息时 MessageQueue ,其 MessageReadPropertyFilter 属性确定检索消息的属性。

MessageQueueSend的方法允许为发送到该队列的消息指定任何对象类型。 可以使用 MessageQueue 实例 DefaultPropertiesToSend 的属性指定发送到队列的泛型消息的设置。 设置的类型包括格式化程序、标签、加密和身份验证。 还可以在协调消息应用程序以响应确认和报告消息时为相应的 DefaultPropertiesToSend 成员指定值。 Message使用实例向队列发送消息可以灵活地访问和修改其中许多属性,无论是针对单个消息还是逐条消息。 Message 属性优先于 DefaultPropertiesToSend.

消息数据存储在属性中 Body ,并且存储到较小的范围 AppSpecificExtension 属性。 加密、序列化或反序列化消息数据时,仅影响属性的内容 Body

使用Formatter指定的属性在发送消息时序列化属性的内容Body。 在属性中找到 BodyStream 序列化的内容。 还可以直接设置 BodyStream 属性,例如,将文件作为消息的数据内容发送。 可以在发送消息之前随时更改 BodyFormatter 属性,并在调用 Send时适当序列化数据。

属性定义的 MessageQueue.DefaultPropertiesToSend 属性仅适用于类型不相同的 Message消息。 如果为 a MessageQueue指定DefaultPropertiesToSend属性,则发送到该队列的实例中Message具有相同命名的属性会导致忽略这些默认属性。

有关实例 Message的初始属性值列表,请参阅 Message 构造函数。

构造函数

名称 说明
Message()

使用空正文初始化类的新实例 Message

Message(Object, IMessageFormatter)

使用指定的格式化程序将指定的对象序列化为消息正文,初始化类的新实例 Message

Message(Object)

使用XmlMessageFormatter将指定对象序列化为消息正文来初始化类的新实例Message

字段

名称 说明
InfiniteTimeout

指定不存在超时。

属性

名称 说明
AcknowledgeType

获取或设置要返回到发送应用程序的确认消息的类型。

Acknowledgment

获取此消息所表示的确认的分类。

AdministrationQueue

获取或设置接收消息队列生成的确认消息的队列。

AppSpecific

获取或设置其他特定于应用程序的信息。

ArrivedTime

获取消息到达目标队列的时间。

AttachSenderId

获取或设置一个值,该值指示是否应将发件人 ID 附加到邮件。

Authenticated

获取一个值,该值指示是否对消息进行身份验证。

AuthenticationProviderName

获取或设置用于生成消息数字签名的加密提供程序的名称。

AuthenticationProviderType

获取或设置用于生成消息数字签名的加密提供程序的类型。

Body

获取或设置消息的内容。

BodyStream

获取或设置消息正文中的信息。

BodyType

获取或设置消息正文包含的数据类型。

CanRaiseEvents

获取一个值,该值指示组件是否可以引发事件。

(继承自 Component)
ConnectorType

获取或设置一个值,该值指示通常由消息队列设置的某些消息属性是由发送应用程序设置的。

Container

IContainer获取包含 .Component

(继承自 Component)
CorrelationId

获取或设置确认、报告和响应消息用来引用原始消息的消息标识符。

DesignMode

获取一个值,该值指示当前是否 Component 处于设计模式。

(继承自 Component)
DestinationQueue

获取消息的预期目标队列。

DestinationSymmetricKey

获取或设置用于加密发送到外部队列的应用程序加密消息或消息的对称密钥。

DigitalSignature

获取或设置消息队列用于对消息进行身份验证的数字签名。

EncryptionAlgorithm

获取或设置用于加密专用消息正文的加密算法。

Events

获取附加到此 Component对象的事件处理程序的列表。

(继承自 Component)
Extension

获取或设置与消息关联的其他应用程序定义信息。

Formatter

获取或设置用于将对象序列化为消息正文中的对象或反序列化对象的格式化程序。

HashAlgorithm

获取或设置消息队列在对消息进行身份验证或为消息创建数字签名时使用的哈希算法。

Id

获取消息的标识符。

IsFirstInTransaction

获取一个值,该值指示消息是否是事务中发送的第一条消息。

IsLastInTransaction

获取一个值,该值指示消息是否是事务中发送的最后一条消息。

Label

获取或设置描述消息的应用程序定义的 Unicode 字符串。

LookupId

MSMQ 3.0 中引入。 获取消息的查找标识符。

MessageType

获取消息类型: NormalAcknowledgmentReport

Priority

获取或设置消息优先级,该优先级确定消息在队列中放置的位置。

Recoverable

获取或设置一个值,该值指示在发生计算机故障或网络问题时是否保证传递消息。

ResponseQueue

获取或设置接收应用程序生成的响应消息的队列。

SecurityContext

获取或设置消息的安全上下文。

SenderCertificate

获取或设置用于对消息进行身份验证的安全证书。

SenderId

获取发送用户的标识符。

SenderVersion

获取用于发送消息的消息队列的版本。

SentTime

获取源队列管理器发送消息的发送计算机上的日期和时间。

Site

获取或设置 ISite .Component

(继承自 Component)
SourceMachine

获取消息源自的计算机。

TimeToBeReceived

获取或设置从目标队列接收消息的最大时间量。

TimeToReachQueue

获取或设置消息到达队列的最大时间量。

TransactionId

获取消息所属事务的标识符。

TransactionStatusQueue

获取源计算机上的事务状态队列。

UseAuthentication

获取或设置一个值,该值指示在发送消息之前是否经过身份验证(或必须进行身份验证)。

UseDeadLetterQueue

获取或设置一个值,该值指示是否应将无法传递的消息副本发送到死信队列。

UseEncryption

获取或设置一个值,该值指示是否将消息设为私有。

UseJournalQueue

获取或设置一个值,该值指示消息的副本是否应保存在原始计算机上的计算机日记中。

UseTracing

获取或设置一个值,该值指示在消息向目标队列移动时是否跟踪消息。

方法

名称 说明
CreateObjRef(Type)

创建一个对象,其中包含生成用于与远程对象通信的代理所需的所有相关信息。

(继承自 MarshalByRefObject)
Dispose()

释放该 Component命令使用的所有资源。

(继承自 Component)
Dispose(Boolean)

释放由托管资源使用 Component 的非托管资源,并选择性地释放托管资源。

(继承自 Component)
Equals(Object)

确定指定的对象是否等于当前对象。

(继承自 Object)
GetHashCode()

用作默认哈希函数。

(继承自 Object)
GetLifetimeService()
已过时.

检索控制此实例的生存期策略的当前生存期服务对象。

(继承自 MarshalByRefObject)
GetService(Type)

返回一个对象,该对象表示服务由 Component 或其 Container提供的服务。

(继承自 Component)
GetType()

获取当前实例的 Type

(继承自 Object)
InitializeLifetimeService()
已过时.

获取生存期服务对象来控制此实例的生存期策略。

(继承自 MarshalByRefObject)
MemberwiseClone()

创建当前 Object的浅表副本。

(继承自 Object)
MemberwiseClone(Boolean)

创建当前 MarshalByRefObject 对象的浅表副本。

(继承自 MarshalByRefObject)
ToString()

返回包含 String 的名称 Component(如果有)。 不应重写此方法。

(继承自 Component)

活动

名称 说明
Disposed

当组件通过对方法的调用 Dispose() 释放时发生。

(继承自 Component)

适用于

另请参阅