MessageQueue.Receive 方法

定义

接收队列中的第一条消息,但不将它从队列中移除。Receives the first message in the queue, removing it from the queue.

重载

Receive()

接收 MessageQueue 引用的队列中可用的第一条消息。Receives the first message available in the queue referenced by the MessageQueue. 此调用是同步的,在有可用消息前,它将一直阻止当前线程的执行。This call is synchronous, and blocks the current thread of execution until a message is available.

Receive(MessageQueueTransaction)

接收 MessageQueue 引用的事务性队列中可用的第一条消息。Receives the first message available in the transactional queue referenced by the MessageQueue. 此调用是同步的,在有可用消息前,它将一直阻止当前线程的执行。This call is synchronous, and blocks the current thread of execution until a message is available.

Receive(MessageQueueTransactionType)

接收 MessageQueue 引用的队列中可用的第一条消息。Receives the first message available in the queue referenced by the MessageQueue. 此调用是同步的,在有可用消息前,它将一直阻止当前线程的执行。This call is synchronous, and blocks the current thread of execution until a message is available.

Receive(TimeSpan)

接收由 MessageQueue 引用的队列中的第一条可用消息,并且一直等到队列中有可用消息或超时过期。Receives the first message available in the queue referenced by the MessageQueue and waits until either a message is available in the queue, or the time-out expires.

Receive(TimeSpan, Cursor)

使用指定的游标接收队列中的当前消息。Receives the current message in the queue, using a specified cursor. 如果没有可用的消息,此方法将等待,直到有可用的消息或超时到期为止。If no message is available, this method waits until either a message is available, or the time-out expires.

Receive(TimeSpan, MessageQueueTransaction)

接收由 MessageQueue 引用的事务性队列中的第一条可用消息,并且一直等到队列中有可用消息或超时过期。Receives the first message available in the transactional queue referenced by the MessageQueue and waits until either a message is available in the queue, or the time-out expires.

Receive(TimeSpan, MessageQueueTransactionType)

接收 MessageQueue 引用的队列中可用的第一条消息。Receives the first message available in the queue referenced by the MessageQueue. 此调用是同步的,并且一直等到队列中有可用的消息或超时到期。This call is synchronous, and waits until either a message is available in the queue, or the time-out expires.

Receive(TimeSpan, Cursor, MessageQueueTransaction)

使用指定的游标接收队列中的当前消息。Receives the current message in the queue, using a specified cursor. 如果没有可用的消息,此方法将等待,直到有可用的消息或超时到期为止。If no message is available, this method waits until either a message is available, or the time-out expires.

Receive(TimeSpan, Cursor, MessageQueueTransactionType)

使用指定的游标接收队列中的当前消息。Receives the current message in the queue, using a specified cursor. 如果没有可用的消息,此方法将等待,直到有可用的消息或超时到期为止。If no message is available, this method waits until either a message is available, or the time-out expires.

Receive()

接收 MessageQueue 引用的队列中可用的第一条消息。Receives the first message available in the queue referenced by the MessageQueue. 此调用是同步的,在有可用消息前,它将一直阻止当前线程的执行。This call is synchronous, and blocks the current thread of execution until a message is available.

public:
 System::Messaging::Message ^ Receive();
public System.Messaging.Message Receive ();
member this.Receive : unit -> System.Messaging.Message
Public Function Receive () As Message

返回

Message

Message,它引用队列中可用的第一条消息。A Message that references the first message available in the queue.

例外

访问“消息队列”方法时出错。An error occurred when accessing a Message Queuing method.

示例

下面的代码示例接收队列中的消息,并将有关该消息的信息输出到屏幕。The following code example receives a message from a queue and outputs information about that message to the screen.

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

using namespace System;
using namespace System::Messaging;

// This class represents an object the following example 
// sends to a queue and receives from a queue.
ref class Order
{
public:
   int orderId;
   DateTime orderTime;
};


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

   //*************************************************
   // Sends an Order to a queue.
   //*************************************************
   void SendMessage()
   {
      // 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" );

      // Send the Order to the queue.
      myQueue->Send( sentOrder );
      return;
   }

   //*************************************************
   // Receives a message containing an Order.
   //*************************************************
   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 = static_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;
   }
};

//*************************************************
// Provides an entry point into the application.
//         
// This example sends and receives a message from
// a queue.
//*************************************************
int main()
{
   // Create a new instance of the class.
   MyNewQueue^ myNewQueue = gcnew MyNewQueue;

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

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

namespace MyProject
{

    // This class represents an object 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();

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

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

            return;
        }

        //**************************************************
        // Sends an Order to a queue.
        //**************************************************
        
        public void SendMessage()
        {
            
            // 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");

            // Send the Order to the queue.
            myQueue.Send(sentOrder);

            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

    ' This class represents an object 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


   
    Public Class MyNewQueue


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

        Public Shared Sub Main()

            ' Create a new instance of the class.
            Dim myNewQueue As New MyNewQueue()

            ' Send a message to a queue.
            myNewQueue.SendMessage()

            ' Receive a message from a queue.
            myNewQueue.ReceiveMessage()

            Return

        End Sub


        '
        ' Sends an Order to a queue.
        '

        Public Sub SendMessage()

            ' 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")

            ' Send the Order to the queue.
            myQueue.Send(sentOrder)

            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 the 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()))

            Catch m As MessageQueueException
                ' Handle Message Queuing exceptions.

            Catch e As InvalidOperationException
                ' Handle invalid serialization format.
                Console.WriteLine(e.Message)


                ' Catch other exceptions as necessary.

            End Try

            Return

        End Sub

End Class

注解

使用此重载接收队列中的消息,或等待队列中有消息。Use this overload to receive a message from a queue, or wait until there are messages in the queue.

Receive方法允许同步读取消息,从而将其从队列中删除。The Receive method allows for the synchronous reading of a message, thereby removing it from the queue. 对的后续调用 Receive 将返回队列中后面的消息或新的优先级较高的消息。Subsequent calls to Receive will return the messages that follow in the queue, or new, higher priority messages.

若要读取队列中的第一条消息而不将其从队列中删除,请使用 Peek 方法。To read the first message in a queue without removing it from the queue, use the Peek method. Peek方法始终返回队列中的第一条消息,因此,对方法的后续调用将返回相同的消息,除非队列中有较高优先级的消息到达。The Peek method always returns the first message in the queue, so subsequent calls to the method return the same message unless a higher priority message arrives in the queue.

Receive如果当前线程在等待消息到达队列时可以被阻塞,则使用对的调用。Use a call to Receive when it is acceptable for the current thread to be blocked while it waits for a message to arrive in the queue. 由于此方法的重载 Receive 指定一个无限超时,因此应用程序可能会无限期等待。Because this overload of the Receive method specifies an infinite time-out, the application might wait indefinitely. 如果应用程序处理应继续而不等待消息,请考虑使用异步方法 BeginReceiveIf the application processing should continue without waiting for the message, consider using the asynchronous method, BeginReceive.

下表显示了此方法是否在各种工作组模式下可用。The following table shows whether this method is available in various Workgroup modes.

工作组模式Workgroup mode 可用Available
本地计算机Local computer Yes
本地计算机和直接格式名称Local computer and direct format name Yes
远程计算机Remote computer No
远程计算机和直接格式名称Remote computer and direct format name Yes

另请参阅

适用于

Receive(MessageQueueTransaction)

接收 MessageQueue 引用的事务性队列中可用的第一条消息。Receives the first message available in the transactional queue referenced by the MessageQueue. 此调用是同步的,在有可用消息前,它将一直阻止当前线程的执行。This call is synchronous, and blocks the current thread of execution until a message is available.

public:
 System::Messaging::Message ^ Receive(System::Messaging::MessageQueueTransaction ^ transaction);
public System.Messaging.Message Receive (System.Messaging.MessageQueueTransaction transaction);
member this.Receive : System.Messaging.MessageQueueTransaction -> System.Messaging.Message
Public Function Receive (transaction As MessageQueueTransaction) As Message

参数

返回

Message

Message,它引用队列中可用的第一条消息。A Message that references the first message available in the queue.

例外

访问“消息队列”方法时出错。An error occurred when accessing a Message Queuing method.

- 或 --or-

该队列为非事务性队列。The queue is non-transactional.

示例

下面的代码示例连接到本地计算机上的事务队列,并将消息发送到队列。The following code example connects to a transactional queue on the local computer and sends a message to the queue. 然后,它将接收包含订单的消息。It then receives the message that contains an order. 如果遇到非事务性队列,它将引发并引发异常并回滚事务。If it encounters a non-transactional queue, it will throw and exception and rollback the transaction.

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

using namespace System;
using namespace System::Messaging;

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

   //*************************************************
   // Sends a message to a queue.
   //*************************************************
   void SendMessageTransactional()
   {
      // Connect to a queue on the local computer.
      MessageQueue^ myQueue = gcnew MessageQueue( ".\\myTransactionalQueue" );

      // Send a message to the queue.
      if ( myQueue->Transactional == true )
      {
         // Create a transaction.
         MessageQueueTransaction^ myTransaction = gcnew MessageQueueTransaction;

         // Begin the transaction.
         myTransaction->Begin();

         // Send the message.
         myQueue->Send( "My Message Data.", myTransaction );

         // Commit the transaction.
         myTransaction->Commit();
      }

      return;
   }


   //*************************************************
   // Receives a message containing an Order.
   //*************************************************
   void ReceiveMessageTransactional()
   {
      // Connect to a transactional queue on the local computer.
      MessageQueue^ myQueue = gcnew MessageQueue( ".\\myTransactionalQueue" );

      // Set the formatter.
      array<Type^>^p = gcnew array<Type^>(1);
      p[ 0 ] = String::typeid;
      myQueue->Formatter = gcnew XmlMessageFormatter( p );

      // Create a transaction.
      MessageQueueTransaction^ myTransaction = gcnew MessageQueueTransaction;
      try
      {
         // Begin the transaction.
         myTransaction->Begin();

         // Receive the message. 
         Message^ myMessage = myQueue->Receive( myTransaction );
         String^ myOrder = static_cast<String^>(myMessage->Body);

         // Display message information.
         Console::WriteLine( myOrder );

         // Commit the transaction.
         myTransaction->Commit();
      }
      catch ( MessageQueueException^ e ) 
      {
         // Handle nontransactional queues.
         if ( e->MessageQueueErrorCode == MessageQueueErrorCode::TransactionUsage )
         {
            Console::WriteLine( "Queue is not transactional." );
         }

         // Else catch other sources of a MessageQueueException.
         // Roll back the transaction.
         myTransaction->Abort();
      }

      // Catch other exceptions as necessary, such as 
      // InvalidOperationException, thrown when the formatter 
      // cannot deserialize the message.
      return;
   }
};

//*************************************************
// Provides an entry point into the application.
// 
// This example sends and receives a message from
// a transactional queue.
//*************************************************
int main()
{
   // Create a new instance of the class.
   MyNewQueue^ myNewQueue = gcnew MyNewQueue;

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

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

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 transactional queue.
        //**************************************************

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

            // Send a message to a queue.
            myNewQueue.SendMessageTransactional();

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

            return;
        }

        //**************************************************
        // Sends a message to a queue.
        //**************************************************
        
        public void SendMessageTransactional()
        {
                        
            // Connect to a queue on the local computer.
            MessageQueue myQueue = new
                MessageQueue(".\\myTransactionalQueue");

            // Send a message to the queue.
            if (myQueue.Transactional == true)
            {
                // Create a transaction.
                MessageQueueTransaction myTransaction = new
                    MessageQueueTransaction();

                // Begin the transaction.
                myTransaction.Begin();

                // Send the message.
                myQueue.Send("My Message Data.", myTransaction);

                // Commit the transaction.
                myTransaction.Commit();
            }

            return;
        }

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

            // Set the formatter.
            myQueue.Formatter = new XmlMessageFormatter(new Type[]
                {typeof(String)});
            
            // Create a transaction.
            MessageQueueTransaction myTransaction = new
                MessageQueueTransaction();

            try
            {
                // Begin the transaction.
                myTransaction.Begin();
                
                // Receive the message.
                Message myMessage =	myQueue.Receive(myTransaction);
                String myOrder = (String)myMessage.Body;

                // Display message information.
                Console.WriteLine(myOrder);

                // Commit the transaction.
                myTransaction.Commit();
            }
            
            catch (MessageQueueException e)
            {
                // Handle nontransactional queues.
                if (e.MessageQueueErrorCode ==
                    MessageQueueErrorCode.TransactionUsage)
                {
                    Console.WriteLine("Queue is not transactional.");
                }
                
                // Else catch other sources of a MessageQueueException.

                // Roll back the transaction.
                myTransaction.Abort();
            }

            // Catch other exceptions as necessary, such as
            // InvalidOperationException, thrown when the formatter
            // cannot deserialize the message.

            return;
        }
    }
}
Imports System.Messaging

Public Class MyNewQueue


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

        Public Shared Sub Main()

            ' Create a new instance of the class.
            Dim myNewQueue As New MyNewQueue

            ' Send a message to a queue.
            myNewQueue.SendMessageTransactional()

            ' Receive a message from a queue.
            myNewQueue.ReceiveMessageTransactional()

            Return

        End Sub


        '
        ' Sends a message to a queue.
        '

        Public Sub SendMessageTransactional()

            ' Connect to a queue on the local computer.
            Dim myQueue As New MessageQueue(".\myTransactionalQueue")

            ' Send a message to the queue.
            If myQueue.Transactional = True Then

                ' Create a transaction.
                Dim myTransaction As New MessageQueueTransaction

                ' Begin the transaction.
                myTransaction.Begin()

                ' Send the message.
                myQueue.Send("My Message Data.", myTransaction)

                ' Commit the transaction.
                myTransaction.Commit()

            End If

            Return

        End Sub


        '
        ' Receives a message containing an Order.
        '

        Public Sub ReceiveMessageTransactional()

            ' Connect to a transactional queue on the local computer.
            Dim myQueue As New MessageQueue(".\myTransactionalQueue")

            ' Set the formatter.
            myQueue.Formatter = New XmlMessageFormatter(New Type() _
                {GetType([String])})

            ' Create a transaction.
            Dim myTransaction As New MessageQueueTransaction

            Try

                ' Begin the transaction.
                myTransaction.Begin()

                ' Receive the message. 
                Dim myMessage As Message = _
                    myQueue.Receive(myTransaction)
                Dim myOrder As [String] = CType(myMessage.Body, _
                    [String])

                ' Display message information.
                Console.WriteLine(myOrder)

                ' Commit the transaction.
                myTransaction.Commit()


            Catch e As MessageQueueException

                ' Handle nontransactional queues.
                If e.MessageQueueErrorCode = _
                    MessageQueueErrorCode.TransactionUsage Then

                    Console.WriteLine("Queue is not transactional.")

                End If

                ' Else catch other sources of a MessageQueueException.


                ' Roll back the transaction.
                myTransaction.Abort()


                ' Catch other exceptions as necessary, such as 
                ' InvalidOperationException, thrown when the formatter
                ' cannot deserialize the message.

            End Try

            Return

        End Sub

End Class

注解

使用此重载可以通过由参数定义的内部事务上下文接收来自事务性队列的消息 transaction ,或等待队列中有消息。Use this overload to receive a message from a transactional queue using the internal transaction context defined by the transaction parameter, or wait until there are messages in the queue.

Receive方法允许同步读取消息,从而将其从队列中删除。The Receive method allows for the synchronous reading of a message, thereby removing it from the queue. 对的后续调用 Receive 将返回队列中后面的消息。Subsequent calls to Receive will return the messages that follow in the queue.

由于此方法是在事务队列中调用的,因此,如果事务中止,接收到的消息将返回到队列。Because this method is called on a transactional queue, the message that is received would be returned to the queue if the transaction is aborted. 在提交事务之前,不会从队列中永久删除该消息。The message is not permanently removed from the queue until the transaction is committed.

若要读取队列中的第一条消息而不将其从队列中删除,请使用 Peek 方法。To read the first message in a queue without removing it from the queue, use the Peek method. Peek方法始终返回队列中的第一条消息,因此,对方法的后续调用将返回相同的消息,除非队列中有较高优先级的消息到达。The Peek method always returns the first message in the queue, so subsequent calls to the method return the same message unless a higher priority message arrives in the queue. 没有与调用返回的消息相关联的事务上下文 PeekThere is no transaction context associated with a message returned by a call to Peek. 由于不会 Peek 删除队列中的任何消息,因此不会通过调用来回滚任何内容 AbortBecause Peek does not remove any messages in the queue, there would be nothing to roll back by a call to Abort.

Receive如果当前线程在等待消息到达队列时可以被阻塞,则使用对的调用。Use a call to Receive when it is acceptable for the current thread to be blocked while it waits for a message to arrive in the queue. 由于此方法的重载 Receive 指定一个无限超时,因此应用程序可能会无限期等待。Because this overload of the Receive method specifies an infinite time-out, the application might wait indefinitely. 如果应用程序处理应继续而不等待消息,请考虑使用异步方法 BeginReceiveIf the application processing should continue without waiting for the message, consider using the asynchronous method, BeginReceive.

下表显示了此方法是否在各种工作组模式下可用。The following table shows whether this method is available in various Workgroup modes.

工作组模式Workgroup mode 可用Available
本地计算机Local computer Yes
本地计算机和直接格式名称Local computer and direct format name Yes
远程计算机Remote computer No
远程计算机和直接格式名称Remote computer and direct format name Yes

另请参阅

适用于

Receive(MessageQueueTransactionType)

接收 MessageQueue 引用的队列中可用的第一条消息。Receives the first message available in the queue referenced by the MessageQueue. 此调用是同步的,在有可用消息前,它将一直阻止当前线程的执行。This call is synchronous, and blocks the current thread of execution until a message is available.

public:
 System::Messaging::Message ^ Receive(System::Messaging::MessageQueueTransactionType transactionType);
public System.Messaging.Message Receive (System.Messaging.MessageQueueTransactionType transactionType);
member this.Receive : System.Messaging.MessageQueueTransactionType -> System.Messaging.Message
Public Function Receive (transactionType As MessageQueueTransactionType) As Message

参数

transactionType
MessageQueueTransactionType

MessageQueueTransactionType 值之一,它描述与消息关联的事务上下文的类型。One of the MessageQueueTransactionType values, describing the type of transaction context to associate with the message.

返回

Message

Message,它引用队列中可用的第一条消息。A Message that references the first message available in the queue.

例外

访问“消息队列”方法时出错。An error occurred when accessing a Message Queuing method.

transactionType 参数不是 MessageQueueTransactionType 成员之一。The transactionType parameter is not one of the MessageQueueTransactionType members.

示例

以下代码示例演示了 Receive(MessageQueueTransactionType) 的用法。The following code example demonstrates the use of Receive(MessageQueueTransactionType).


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

// Create a new message.
Message^ msg = gcnew Message("Example Message Body");

// Send the message.
queue->Send(msg, MessageQueueTransactionType::Single);

// Simulate doing other work so the message has time to arrive.
System::Threading::Thread::Sleep(TimeSpan::FromSeconds(10.0));

// Set the formatter to indicate the message body contains a String.
queue->Formatter = gcnew XmlMessageFormatter(
    gcnew array<Type^>{String::typeid});

// Receive the message from the queue.  Because the Id of the message
// , it might not be the message just sent.
msg = queue->Receive(MessageQueueTransactionType::Single);

queue->Close();


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

// Create a new message.
Message msg = new Message("Example Message Body");

// Send the message.
queue.Send(msg, MessageQueueTransactionType.Single);

// Simulate doing other work so the message has time to arrive.
System.Threading.Thread.Sleep(TimeSpan.FromSeconds(10.0));

// Set the formatter to indicate the message body contains a String.
queue.Formatter = new XmlMessageFormatter(new Type[]
    {typeof(String)});

// Receive the message from the queue.  Because the Id of the message
// , it might not be the message just sent.
msg = queue.Receive(MessageQueueTransactionType.Single);

注解

使用此重载通过由参数定义的事务上下文从队列中接收消息 transactionType ,或等待队列中有消息。Use this overload to receive a message from a queue using a transaction context defined by the transactionType parameter, or wait until there are messages in the queue.

Automatic transactionType 如果已存在附加到要用于接收消息的线程的外部事务上下文,请为参数指定。Specify Automatic for the transactionType parameter if there is already an external transaction context attached to the thread that you want to use to receive the message. 指定 Single 是否要以单个内部事务的形式接收消息。Specify Single if you want to receive the message as a single internal transaction. 您可以指定 None 是否要在事务上下文之外接收来自事务性队列的消息。You can specify None if you want to receive a message from a transactional queue outside of a transaction context.

Receive方法允许同步读取消息,从而将其从队列中删除。The Receive method allows for the synchronous reading of a message, thereby removing it from the queue. 对的后续调用 Receive 将返回队列中后面的消息。Subsequent calls to Receive will return the messages that follow in the queue.

如果调用此方法来接收来自事务性队列的消息,则在事务中止时,收到的消息将返回到队列。If this method is called to receive a message from a transactional queue, the message that is received would be returned to the queue if the transaction is aborted. 在提交事务之前,不会从队列中永久删除该消息。The message is not permanently removed from the queue until the transaction is committed.

若要读取队列中的第一条消息而不将其从队列中删除,请使用 Peek 方法。To read the first message in a queue without removing it from the queue, use the Peek method. Peek方法始终返回队列中的第一条消息,因此,对方法的后续调用将返回相同的消息,除非队列中有较高优先级的消息到达。The Peek method always returns the first message in the queue, so subsequent calls to the method return the same message unless a higher priority message arrives in the queue. 没有与调用返回的消息相关联的事务上下文 PeekThere is no transaction context associated with a message returned by a call to Peek. 由于不会 Peek 删除队列中的任何消息,因此不会通过调用来回滚任何内容 AbortBecause Peek does not remove any messages in the queue, there would be nothing to roll back by a call to Abort.

Receive如果当前线程在等待消息到达队列时可以被阻塞,则使用对的调用。Use a call to Receive when it is acceptable for the current thread to be blocked while it waits for a message to arrive in the queue. 由于此方法的重载 Receive 指定一个无限超时,因此应用程序可能会无限期等待。Because this overload of the Receive method specifies an infinite time-out, the application might wait indefinitely. 如果应用程序处理应继续而不等待消息,请考虑使用异步方法 BeginReceiveIf the application processing should continue without waiting for the message, consider using the asynchronous method, BeginReceive.

下表显示了此方法是否在各种工作组模式下可用。The following table shows whether this method is available in various Workgroup modes.

工作组模式Workgroup mode 可用Available
本地计算机Local computer Yes
本地计算机和直接格式名称Local computer and direct format name Yes
远程计算机Remote computer No
远程计算机和直接格式名称Remote computer and direct format name Yes

另请参阅

适用于

Receive(TimeSpan)

接收由 MessageQueue 引用的队列中的第一条可用消息,并且一直等到队列中有可用消息或超时过期。Receives the first message available in the queue referenced by the MessageQueue and waits until either a message is available in the queue, or the time-out expires.

public:
 System::Messaging::Message ^ Receive(TimeSpan timeout);
public System.Messaging.Message Receive (TimeSpan timeout);
member this.Receive : TimeSpan -> System.Messaging.Message
Public Function Receive (timeout As TimeSpan) As Message

参数

timeout
TimeSpan

一个 TimeSpan 指示有新消息可用于检查之前等待的时间。A TimeSpan that indicates the time to wait until a new message is available for inspection.

返回

Message

Message,它引用队列中可用的第一条消息。A Message that references the first message available in the queue.

例外

timeout 参数指定的值无效,可能是 timeout 小于 Zero 或大于 InfiniteTimeoutThe value specified for the timeout parameter is not valid, possibly timeout is less than Zero or greater than InfiniteTimeout.

在超时过期之前消息没有到达队列。A message did not arrive in the queue before the time-out expired.

- 或 --or-

访问“消息队列”方法时出错。An error occurred when accessing a Message Queuing method

示例

下面的代码示例接收队列中的消息,并将有关该消息的信息输出到屏幕。The following code example receives a message from a queue and outputs information about that message to the screen. 该示例在等待消息到达队列时,暂停执行最多5秒。The example pauses execution for up to five seconds while waiting for a message to arrive in the queue.

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

using namespace System;
using namespace System::Messaging;

// This class represents an object the following example 
// receives from a queue.
ref class Order
{
public:
   int orderId;
   DateTime orderTime;
};


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

   //*************************************************
   // Receives a message containing an Order.
   //*************************************************
   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. 
         // Wait 5 seconds for a message to arrive.
         Message^ myMessage = myQueue->Receive( TimeSpan(0,0,5) );
         Order^ myOrder = static_cast<Order^>(myMessage->Body);

         // Display message information.
         Console::WriteLine( "Order ID: {0}", myOrder->orderId );
         Console::WriteLine( "Sent: {0}", myOrder->orderTime );
      }
      catch ( MessageQueueException^ e ) 
      {
         // Handle no message arriving in the queue.
         if ( e->MessageQueueErrorCode == MessageQueueErrorCode::IOTimeout )
         {
            Console::WriteLine( "No message arrived in queue." );
         }

         // Handle other sources of a MessageQueueException.
      }
      // Handle invalid serialization format.
      catch ( InvalidOperationException^ e ) 
      {
         Console::WriteLine( e->Message );
      }

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

//*************************************************
// Provides an entry point into the application.
//         
// This example receives a message from a queue.
//*************************************************
int main()
{
   // Create a new instance of the class.
   MyNewQueue^ myNewQueue = gcnew MyNewQueue;

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

namespace MyProject
{
    // This class represents an object the following example
    // 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 receives a message from a queue.
        //**************************************************

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

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

            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.
                // Wait 5 seconds for a message to arrive.
                Message myMessage =	myQueue.Receive(new
                    TimeSpan(0,0,5));
                Order myOrder = (Order)myMessage.Body;

                // Display message information.
                Console.WriteLine("Order ID: " +
                    myOrder.orderId.ToString());
                Console.WriteLine("Sent: " +
                    myOrder.orderTime.ToString());
            }

            catch (MessageQueueException e)
            {
                // Handle no message arriving in the queue.
                if (e.MessageQueueErrorCode ==
                    MessageQueueErrorCode.IOTimeout)
                {
                    Console.WriteLine("No message arrived in queue.");
                }			

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

            return;
        }
    }
}
Imports System.Messaging

' This class represents an object the following example 
' receives from a queue.
Public Class Order
        Public orderId As Integer
        Public orderTime As DateTime
End Class


   
Public Class MyNewQueue


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

        Public Shared Sub Main()

            ' Create a new instance of the class.
            Dim myNewQueue As New MyNewQueue()

            ' Receive a message from a queue.
            myNewQueue.ReceiveMessage()

            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. 
                ' Wait 5 seconds for a message to arrive.
                Dim myMessage As Message = myQueue.Receive(New _
                    TimeSpan(0, 0, 5))
                Dim myOrder As Order = CType(myMessage.Body, Order)

                ' Display message information.
                Console.WriteLine(("Order ID: " + _
                    myOrder.orderId.ToString()))
                Console.WriteLine(("Sent: " + _
                    myOrder.orderTime.ToString()))

            Catch e As MessageQueueException
                ' Handle no message arriving in the queue.
                If e.MessageQueueErrorCode = _
                    MessageQueueErrorCode.IOTimeout Then

                    Console.WriteLine("No message arrived in queue.")

                End If

                ' Handle other sources of a MessageQueueException.

            Catch e As InvalidOperationException
                ' Handle invalid serialization format.
                Console.WriteLine(e.Message)

                ' Catch other exceptions as necessary.

            End Try

            Return

        End Sub

End Class

注解

使用此重载接收消息并在队列中没有消息时在指定的时间段内返回。Use this overload to receive a message and return in a specified period of time if there are no messages in the queue.

Receive方法允许同步读取消息,并将其从队列中删除。The Receive method allows for the synchronous reading of a message, removing it from the queue. 对的后续调用 Receive 将返回队列中后面的消息或新的优先级较高的消息。Subsequent calls to Receive will return the messages that follow in the queue, or new, higher priority messages.

若要读取队列中的第一条消息而不将其从队列中删除,请使用 Peek 方法。To read the first message in a queue without removing it from the queue, use the Peek method. Peek方法始终返回队列中的第一条消息,因此,对方法的后续调用将返回相同的消息,除非队列中有较高优先级的消息到达。The Peek method always returns the first message in the queue, so subsequent calls to the method return the same message unless a higher priority message arrives in the queue.

Receive如果当前线程在等待消息到达队列时可以被阻塞,则使用对的调用。Use a call to Receive when it is acceptable for the current thread to be blocked while it waits for a message to arrive in the queue. 如果为参数指定了值,则线程将在给定的时间段内被阻止,或无限期地阻止 InfiniteTimeout timeoutThe thread will be blocked for the given period of time, or indefinitely if you specified the value InfiniteTimeout for the timeout parameter. 如果应用程序处理应在不等待消息的情况下继续运行,请考虑使用异步方法 BeginReceiveIf the application processing should continue without waiting for a message, consider using the asynchronous method, BeginReceive.

下表显示了此方法是否在各种工作组模式下可用。The following table shows whether this method is available in various Workgroup modes.

工作组模式Workgroup mode 可用Available
本地计算机Local computer Yes
本地计算机和直接格式名称Local computer and direct format name Yes
远程计算机Remote computer No
远程计算机和直接格式名称Remote computer and direct format name Yes

另请参阅

适用于

Receive(TimeSpan, Cursor)

使用指定的游标接收队列中的当前消息。Receives the current message in the queue, using a specified cursor. 如果没有可用的消息,此方法将等待,直到有可用的消息或超时到期为止。If no message is available, this method waits until either a message is available, or the time-out expires.

public:
 System::Messaging::Message ^ Receive(TimeSpan timeout, System::Messaging::Cursor ^ cursor);
public System.Messaging.Message Receive (TimeSpan timeout, System.Messaging.Cursor cursor);
member this.Receive : TimeSpan * System.Messaging.Cursor -> System.Messaging.Message
Public Function Receive (timeout As TimeSpan, cursor As Cursor) As Message

参数

timeout
TimeSpan

一个 TimeSpan 指示有新消息可用于检查之前等待的时间。A TimeSpan that indicates the time to wait until a new message is available for inspection.

cursor
Cursor

维持消息队列中特定位置的 CursorA Cursor that maintains a specific position in the message queue.

返回

Message

Message,它引用队列中可用的第一条消息。A Message that references the first message available in the queue.

例外

timeout 参数指定的值无效,可能是 timeout 小于 Zero 或大于 InfiniteTimeoutThe value specified for the timeout parameter is not valid, possibly timeout is less than Zero or greater than InfiniteTimeout.

在超时过期之前消息没有到达队列。A message did not arrive in the queue before the time-out expired.

- 或 --or-

访问“消息队列”方法时出错。An error occurred when accessing a Message Queuing method

使用此重载接收消息并在队列中没有消息时在指定的时间段内返回。Use this overload to receive a message and return in a specified period of time if there are no messages in the queue.

适用于

Receive(TimeSpan, MessageQueueTransaction)

接收由 MessageQueue 引用的事务性队列中的第一条可用消息,并且一直等到队列中有可用消息或超时过期。Receives the first message available in the transactional queue referenced by the MessageQueue and waits until either a message is available in the queue, or the time-out expires.

public:
 System::Messaging::Message ^ Receive(TimeSpan timeout, System::Messaging::MessageQueueTransaction ^ transaction);
public System.Messaging.Message Receive (TimeSpan timeout, System.Messaging.MessageQueueTransaction transaction);
member this.Receive : TimeSpan * System.Messaging.MessageQueueTransaction -> System.Messaging.Message
Public Function Receive (timeout As TimeSpan, transaction As MessageQueueTransaction) As Message

参数

timeout
TimeSpan

一个 TimeSpan 指示有新消息可用于检查之前等待的时间。A TimeSpan that indicates the time to wait until a new message is available for inspection.

返回

Message

Message,它引用队列中可用的第一条消息。A Message that references the first message available in the queue.

例外

timeout 参数指定的值无效,可能是 timeout 小于 Zero 或大于 InfiniteTimeoutThe value specified for the timeout parameter is not valid, possibly timeout is less than Zero or greater than InfiniteTimeout.

在超时过期之前消息没有到达队列。A message did not arrive in the queue before the time-out expired.

- 或 --or-

该队列为非事务性队列。The queue is non-transactional.

- 或 --or-

访问“消息队列”方法时出错。An error occurred when accessing a Message Queuing method.

示例

下面的代码示例演示如何使用此方法。The following code example demonstrates the use of this method.

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

using namespace System;
using namespace System::Messaging;

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

   //*************************************************
   // Sends a message to a transactional queue.
   //*************************************************
   void SendMessageTransactional()
   {
      // Connect to a queue on the local computer.
      MessageQueue^ myQueue = gcnew MessageQueue( ".\\myTransactionalQueue" );

      // Send a message to the queue.
      if ( myQueue->Transactional == true )
      {
         // Create a transaction.
         MessageQueueTransaction^ myTransaction = gcnew MessageQueueTransaction;

         // Begin the transaction.
         myTransaction->Begin();

         // Send the message.
         myQueue->Send( "My Message Data.", myTransaction );

         // Commit the transaction.
         myTransaction->Commit();
      }

      return;
   }

   //*************************************************
   // Receives a message from the transactional queue.
   //*************************************************
   void ReceiveMessageTransactional()
   {
      // Connect to a transactional queue on the local computer.
      MessageQueue^ myQueue = gcnew MessageQueue( ".\\myTransactionalQueue" );

      // Set the formatter.
      array<Type^>^p = gcnew array<Type^>(1);
      p[ 0 ] = String::typeid;
      myQueue->Formatter = gcnew XmlMessageFormatter( p );

      // Create a transaction.
      MessageQueueTransaction^ myTransaction = gcnew MessageQueueTransaction;
      try
      {
         // Begin the transaction.
         myTransaction->Begin();

         // Receive the message. 
         // Wait five seconds for a message to arrive. 
         Message^ myMessage = myQueue->Receive( TimeSpan(0,0,5), myTransaction );
         String^ myOrder = static_cast<String^>(myMessage->Body);

         // Display message information.
         Console::WriteLine( myOrder );

         // Commit the transaction.
         myTransaction->Commit();
      }
      catch ( MessageQueueException^ e ) 
      {
         // Handle nontransactional queues.
         if ( e->MessageQueueErrorCode == MessageQueueErrorCode::TransactionUsage )
         {
            Console::WriteLine( "Queue is not transactional." );
         }
         // Handle no message arriving in the queue.
         else

         // Handle no message arriving in the queue.
         if ( e->MessageQueueErrorCode == MessageQueueErrorCode::IOTimeout )
         {
            Console::WriteLine( "No message in queue." );
         }

         // Else catch other sources of MessageQueueException.
         // Roll back the transaction.
         myTransaction->Abort();
      }

      // Catch other exceptions as necessary, such as 
      // InvalidOperationException, thrown when the formatter 
      // cannot deserialize the message.
      return;
   }
};

//*************************************************
// Provides an entry point into the application.
// 
// This example sends and receives a message from
// a transactional queue.
//*************************************************
int main()
{
   // Create a new instance of the class.
   MyNewQueue^ myNewQueue = gcnew MyNewQueue;

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

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

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 transactional queue.
        //**************************************************

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

            // Send a message to a queue.
            myNewQueue.SendMessageTransactional();

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

            return;
        }

        //**************************************************
        // Sends a message to a transactional queue.
        //**************************************************
        
        public void SendMessageTransactional()
        {
                        
            // Connect to a queue on the local computer.
            MessageQueue myQueue = new
                MessageQueue(".\\myTransactionalQueue");

            // Send a message to the queue.
            if (myQueue.Transactional == true)
            {
                // Create a transaction.
                MessageQueueTransaction myTransaction = new
                    MessageQueueTransaction();

                // Begin the transaction.
                myTransaction.Begin();

                // Send the message.
                myQueue.Send("My Message Data.", myTransaction);

                // Commit the transaction.
                myTransaction.Commit();
            }

            return;
        }

        //**************************************************
        // Receives a message from the transactional queue.
        //**************************************************
        
        public  void ReceiveMessageTransactional()
        {
            // Connect to a transactional queue on the local computer.
            MessageQueue myQueue = new
                MessageQueue(".\\myTransactionalQueue");

            // Set the formatter.
            myQueue.Formatter = new XmlMessageFormatter(new Type[]
                {typeof(String)});
            
            // Create a transaction.
            MessageQueueTransaction myTransaction = new
                MessageQueueTransaction();

            try
            {
                // Begin the transaction.
                myTransaction.Begin();
                
                // Receive the message.
                // Wait five seconds for a message to arrive.
                Message myMessage =	myQueue.Receive(new
                    TimeSpan(0,0,5), myTransaction);
                
                String myOrder = (String)myMessage.Body;

                // Display message information.
                Console.WriteLine(myOrder);

                // Commit the transaction.
                myTransaction.Commit();
            }
            
            catch (MessageQueueException e)
            {
                // Handle nontransactional queues.
                if (e.MessageQueueErrorCode ==
                    MessageQueueErrorCode.TransactionUsage)
                {
                    Console.WriteLine("Queue is not transactional.");
                }

                    // Handle no message arriving in the queue.
                else if (e.MessageQueueErrorCode ==
                    MessageQueueErrorCode.IOTimeout)
                {
                    Console.WriteLine("No message in queue.");
                }
                
                // Else catch other sources of MessageQueueException.

                // Roll back the transaction.
                myTransaction.Abort();
            }

            // Catch other exceptions as necessary, such as
            // InvalidOperationException, thrown when the formatter
            // cannot deserialize the message.

            return;
        }
    }
}
Imports System.Messaging

Namespace MyProj


   
    Public Class MyNewQueue


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

        Public Shared Sub Main()

            ' Create a new instance of the class.
            Dim myNewQueue As New MyNewQueue

            ' Send a message to a queue.
            myNewQueue.SendMessageTransactional()

            ' Receive a message from a queue.
            myNewQueue.ReceiveMessageTransactional()

            Return

        End Sub


        '**************************************************
        ' Sends a message to a transactional queue.
        '**************************************************

        Public Sub SendMessageTransactional()

            ' Connect to a queue on the local computer.
            Dim myQueue As New MessageQueue(".\myTransactionalQueue")

            ' Send a message to the queue.
            If myQueue.Transactional = True Then

                ' Create a transaction.
                Dim myTransaction As New MessageQueueTransaction

                ' Begin the transaction.
                myTransaction.Begin()

                ' Send the message.
                myQueue.Send("My Message Data.", myTransaction)

                ' Commit the transaction.
                myTransaction.Commit()

            End If

            Return

        End Sub


        '**************************************************
        ' Receives a message from the transactional queue.
        '**************************************************

        Public Sub ReceiveMessageTransactional()

            ' Connect to a transactional queue on the local computer.
            Dim myQueue As New MessageQueue(".\myTransactionalQueue")

            ' Set the formatter.
            myQueue.Formatter = New XmlMessageFormatter(New Type() _
                {GetType([String])})

            ' Create a transaction.
            Dim myTransaction As New MessageQueueTransaction

            Try

                ' Begin the transaction.
                myTransaction.Begin()

                ' Receive the message. 
                ' Wait five seconds for a message to arrive. 
                Dim myMessage As Message = myQueue.Receive(New _
                    TimeSpan(0, 0, 5), myTransaction)
                Dim myOrder As [String] = CType(myMessage.Body, _
                    [String])

                ' Display message information.
                Console.WriteLine(myOrder)

                ' Commit the transaction.
                myTransaction.Commit()


            Catch e As MessageQueueException

                ' Handle nontransactional queues.
                If e.MessageQueueErrorCode = _
                    MessageQueueErrorCode.TransactionUsage Then

                    Console.WriteLine("Queue is not transactional.")

                Else
                    ' Handle no message arriving in the queue.
                    If e.MessageQueueErrorCode = _
                        MessageQueueErrorCode.IOTimeout Then

                        Console.WriteLine("No message in queue.")

                    End If
                End If

                ' Else catch other sources of a MessageQueueException.

                ' Roll back the transaction.
                myTransaction.Abort()


                ' Catch other exceptions as necessary, such as InvalidOperationException,
                ' thrown when the formatter cannot deserialize the message.

            End Try

            Return

        End Sub

    End Class
End Namespace 'MyProj

注解

使用此重载,通过由参数定义的内部事务上下文接收来自事务性队列的消息 transaction ,并在队列中没有消息时在指定时间段内返回。Use this overload to receive a message from a transactional queue using the internal transaction context defined by the transaction parameter, and return within a specified period of time if there are no messages in the queue.

Receive方法允许同步读取消息,从而将其从队列中删除。The Receive method allows for the synchronous reading of a message, thereby removing it from the queue. 对的后续调用 Receive 将返回队列中后面的消息。Subsequent calls to Receive will return the messages that follow in the queue.

由于此方法是在事务队列中调用的,因此,如果事务中止,接收到的消息将返回到队列。Because this method is called on a transactional queue, the message that is received would be returned to the queue if the transaction is aborted. 在提交事务之前,不会从队列中永久删除该消息。The message is not permanently removed from the queue until the transaction is committed.

若要读取队列中的第一条消息而不将其从队列中删除,请使用 Peek 方法。To read the first message in a queue without removing it from the queue, use the Peek method. Peek方法始终返回队列中的第一条消息,因此,对方法的后续调用将返回相同的消息,除非队列中有较高优先级的消息到达。The Peek method always returns the first message in the queue, so subsequent calls to the method return the same message unless a higher priority message arrives in the queue. 没有与调用返回的消息相关联的事务上下文 PeekThere is no transaction context associated with a message returned by a call to Peek. 由于不会 Peek 删除队列中的任何消息,因此不会通过调用来回滚任何内容 AbortBecause Peek does not remove any messages in the queue, there would be nothing to roll back by a call to Abort.

Receive如果当前线程在等待消息到达队列时可以被阻塞,则使用对的调用。Use a call to Receive when it is acceptable for the current thread to be blocked while it waits for a message to arrive in the queue. 如果为参数指定了值,则线程将在给定的时间段内被阻止,或无限期地阻止 InfiniteTimeout timeoutThe thread will be blocked for the given period of time, or indefinitely if you specified the value InfiniteTimeout for the timeout parameter. 如果应用程序处理应在不等待消息的情况下继续运行,请考虑使用异步方法 BeginReceiveIf the application processing should continue without waiting for a message, consider using the asynchronous method, BeginReceive.

下表显示了此方法是否在各种工作组模式下可用。The following table shows whether this method is available in various Workgroup modes.

工作组模式Workgroup mode 可用Available
本地计算机Local computer Yes
本地计算机和直接格式名称Local computer and direct format name Yes
远程计算机Remote computer No
远程计算机和直接格式名称Remote computer and direct format name Yes

另请参阅

适用于

Receive(TimeSpan, MessageQueueTransactionType)

接收 MessageQueue 引用的队列中可用的第一条消息。Receives the first message available in the queue referenced by the MessageQueue. 此调用是同步的,并且一直等到队列中有可用的消息或超时到期。This call is synchronous, and waits until either a message is available in the queue, or the time-out expires.

public:
 System::Messaging::Message ^ Receive(TimeSpan timeout, System::Messaging::MessageQueueTransactionType transactionType);
public System.Messaging.Message Receive (TimeSpan timeout, System.Messaging.MessageQueueTransactionType transactionType);
member this.Receive : TimeSpan * System.Messaging.MessageQueueTransactionType -> System.Messaging.Message
Public Function Receive (timeout As TimeSpan, transactionType As MessageQueueTransactionType) As Message

参数

timeout
TimeSpan

一个 TimeSpan 指示有新消息可用于检查之前等待的时间。A TimeSpan that indicates the time to wait until a new message is available for inspection.

transactionType
MessageQueueTransactionType

MessageQueueTransactionType 值之一,它描述与消息关联的事务上下文的类型。One of the MessageQueueTransactionType values, describing the type of transaction context to associate with the message.

返回

Message

Message,它引用队列中可用的第一条消息。A Message that references the first message available in the queue.

例外

timeout 参数指定的值无效,可能是 timeout 小于 Zero 或大于 InfiniteTimeoutThe value specified for the timeout parameter is not valid, possibly timeout is less than Zero or greater than InfiniteTimeout.

transactionType 参数不是 MessageQueueTransactionType 成员之一。The transactionType parameter is not one of the MessageQueueTransactionType members.

在超时过期之前消息没有到达队列。A message did not arrive in the queue before the time-out expired.

- 或 --or-

访问“消息队列”方法时出错。An error occurred when accessing a Message Queuing method.

示例

下面的代码示例演示如何使用此方法。The following code example demonstrates the use of this method.


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

// Create a new message.
Message^ msg = gcnew Message("Example Message Body");

// Send the message.
queue->Send(msg, MessageQueueTransactionType::Single);

// Set the formatter to indicate the message body contains a String.
queue->Formatter = gcnew XmlMessageFormatter(
    gcnew array<Type^>{String::typeid});

// Receive the message from the queue. Because the Id of the message
// is not specified, it might not be the message just sent.
msg = queue->Receive(TimeSpan::FromSeconds(10.0),
    MessageQueueTransactionType::Single);

queue->Close();


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

// Create a new message.
Message msg = new Message("Example Message Body");

// Send the message.
queue.Send(msg, MessageQueueTransactionType.Single);

// Set the formatter to indicate the message body contains a String.
queue.Formatter = new XmlMessageFormatter(new Type[]
    {typeof(String)});

// Receive the message from the queue. Because the Id of the message
// is not specified, it might not be the message just sent.
msg = queue.Receive(TimeSpan.FromSeconds(10.0),
    MessageQueueTransactionType.Single);

注解

使用此重载通过由参数定义的事务上下文从队列中接收消息 transactionType ,并在队列中没有消息时返回指定时间段。Use this overload to receive a message from a queue using a transaction context defined by the transactionType parameter, and return in a specified period of time if there are no messages in the queue.

Automatic transactionType 如果已存在附加到要用于接收消息的线程的外部事务上下文,请为参数指定。Specify Automatic for the transactionType parameter if there is already an external transaction context attached to the thread that you want to use to receive the message. 指定 Single 是否要以单个内部事务的形式接收消息。Specify Single if you want to receive the message as a single internal transaction. 您可以指定 None 是否要在事务上下文之外接收来自事务性队列的消息。You can specify None if you want to receive a message from a transactional queue outside of a transaction context.

Receive方法允许同步读取消息,从而将其从队列中删除。The Receive method allows for the synchronous reading of a message, thereby removing it from the queue. 对的后续调用 Receive 将返回队列中后面的消息。Subsequent calls to Receive will return the messages that follow in the queue.

如果调用此方法来接收来自事务性队列的消息,则在事务中止时,收到的消息将返回到队列。If this method is called to receive a message from a transactional queue, the message that is received would be returned to the queue if the transaction is aborted. 在提交事务之前,不会从队列中永久删除该消息。The message is not permanently removed from the queue until the transaction is committed.

若要读取队列中的第一条消息而不将其从队列中删除,请使用 Peek 方法。To read the first message in a queue without removing it from the queue, use the Peek method. Peek方法始终返回队列中的第一条消息,因此,对方法的后续调用将返回相同的消息,除非队列中有较高优先级的消息到达。The Peek method always returns the first message in the queue, so subsequent calls to the method return the same message unless a higher priority message arrives in the queue. 没有与调用返回的消息相关联的事务上下文 PeekThere is no transaction context associated with a message returned by a call to Peek. 由于不会 Peek 删除队列中的任何消息,因此不会通过调用来回滚任何内容 AbortBecause Peek does not remove any messages in the queue, there would be nothing to roll back by a call to Abort.

Receive如果当前线程在等待消息到达队列时可以被阻塞,则使用对的调用。Use a call to Receive when it is acceptable for the current thread to be blocked while it waits for a message to arrive in the queue. 如果为参数指定了值,则线程将在给定的时间段内被阻止,或无限期地阻止 InfiniteTimeout timeoutThe thread will be blocked for the given period of time, or indefinitely if you specified the value InfiniteTimeout for the timeout parameter. 如果应用程序处理应在不等待消息的情况下继续运行,请考虑使用异步方法 BeginReceiveIf the application processing should continue without waiting for a message, consider using the asynchronous method, BeginReceive.

下表显示了此方法是否在各种工作组模式下可用。The following table shows whether this method is available in various Workgroup modes.

工作组模式Workgroup mode 可用Available
本地计算机Local computer Yes
本地计算机和直接格式名称Local computer and direct format name Yes
远程计算机Remote computer No
远程计算机和直接格式名称Remote computer and direct format name Yes

另请参阅

适用于

Receive(TimeSpan, Cursor, MessageQueueTransaction)

使用指定的游标接收队列中的当前消息。Receives the current message in the queue, using a specified cursor. 如果没有可用的消息,此方法将等待,直到有可用的消息或超时到期为止。If no message is available, this method waits until either a message is available, or the time-out expires.

public:
 System::Messaging::Message ^ Receive(TimeSpan timeout, System::Messaging::Cursor ^ cursor, System::Messaging::MessageQueueTransaction ^ transaction);
public System.Messaging.Message Receive (TimeSpan timeout, System.Messaging.Cursor cursor, System.Messaging.MessageQueueTransaction transaction);
member this.Receive : TimeSpan * System.Messaging.Cursor * System.Messaging.MessageQueueTransaction -> System.Messaging.Message
Public Function Receive (timeout As TimeSpan, cursor As Cursor, transaction As MessageQueueTransaction) As Message

参数

timeout
TimeSpan

一个 TimeSpan 指示有新消息可用于检查之前等待的时间。A TimeSpan that indicates the time to wait until a new message is available for inspection.

cursor
Cursor

维持消息队列中特定位置的 CursorA Cursor that maintains a specific position in the message queue.

返回

Message

一个 Message,它引用队列中的一条消息。A Message that references a message in the queue.

例外

cursor 参数为 nullThe cursor parameter is null.

- 或 --or- transaction 参数为 nullThe transaction parameter is null.

timeout 参数指定的值无效。The value specified for the timeout parameter is not valid. timeout 可能小于 Zero 或大于 InfiniteTimeoutPossibly timeout is less than Zero or greater than InfiniteTimeout.

在超时过期之前消息没有到达队列。A message did not arrive in the queue before the time-out expired.

- 或 --or-

该队列为非事务性队列。The queue is non-transactional.

- 或 --or-

访问“消息队列”方法时出错。An error occurred when accessing a Message Queuing method.

注解

使用此重载,通过由参数定义的内部事务上下文接收来自事务性队列的消息 transaction ,并在队列中没有消息时在指定时间段内返回。Use this overload to receive a message from a transactional queue using the internal transaction context defined by the transaction parameter, and return within a specified period of time if there are no messages in the queue.

Receive方法允许同步读取消息,从而将其从队列中删除。The Receive method allows for the synchronous reading of a message, thereby removing it from the queue. 后续调用 Receive 会返回队列中后面的消息。Subsequent calls to Receive return the messages that follow in the queue.

由于此方法是在事务队列中调用的,因此,如果事务中止,接收到的消息将返回到队列。Because this method is called on a transactional queue, the message that is received is returned to the queue if the transaction is aborted. 在提交事务之前,不会从队列中永久删除该消息。The message is not permanently removed from the queue until the transaction is committed.

若要在队列中读取消息而不将其从队列中删除,请使用 Peek 方法。To read a message in a queue without removing it from the queue, use the Peek method. 没有与调用返回的消息相关联的事务上下文 PeekThere is no transaction context associated with a message returned by a call to Peek. 由于不 Peek 会删除队列中的任何消息,因此没有任何内容可以通过调用回滚 AbortBecause Peek does not remove any messages in the queue, there is nothing to roll back by a call to Abort.

Receive如果当前线程在等待消息到达队列时可以被阻塞,则使用对的调用。Use a call to Receive when it is acceptable for the current thread to be blocked while it waits for a message to arrive in the queue. 线程在给定的时间段内被阻止,或在指定了参数的值的情况下无限期阻止 InfiniteTimeout timeoutThe thread is blocked for the given period of time, or indefinitely if you specified the value InfiniteTimeout for the timeout parameter. 如果应用程序处理应在不等待消息的情况下继续运行,请考虑使用异步方法 BeginReceiveIf the application processing should continue without waiting for a message, consider using the asynchronous method, BeginReceive.

下表显示了此方法是否在各种工作组模式下可用。The following table shows whether this method is available in various Workgroup modes.

工作组模式Workgroup mode 可用Available
本地计算机Local computer Yes
本地计算机和直接格式名称Local computer and direct format name Yes
远程计算机Remote computer No
远程计算机和直接格式名称Remote computer and direct format name Yes

另请参阅

适用于

Receive(TimeSpan, Cursor, MessageQueueTransactionType)

使用指定的游标接收队列中的当前消息。Receives the current message in the queue, using a specified cursor. 如果没有可用的消息,此方法将等待,直到有可用的消息或超时到期为止。If no message is available, this method waits until either a message is available, or the time-out expires.

public:
 System::Messaging::Message ^ Receive(TimeSpan timeout, System::Messaging::Cursor ^ cursor, System::Messaging::MessageQueueTransactionType transactionType);
public System.Messaging.Message Receive (TimeSpan timeout, System.Messaging.Cursor cursor, System.Messaging.MessageQueueTransactionType transactionType);
member this.Receive : TimeSpan * System.Messaging.Cursor * System.Messaging.MessageQueueTransactionType -> System.Messaging.Message
Public Function Receive (timeout As TimeSpan, cursor As Cursor, transactionType As MessageQueueTransactionType) As Message

参数

timeout
TimeSpan

一个 TimeSpan 指示有新消息可用于检查之前等待的时间。A TimeSpan that indicates the time to wait until a new message is available for inspection.

cursor
Cursor

维持消息队列中特定位置的 CursorA Cursor that maintains a specific position in the message queue.

transactionType
MessageQueueTransactionType

MessageQueueTransactionType 值之一,它描述与消息关联的事务上下文类型。One of the MessageQueueTransactionType values that describes the type of transaction context to associate with the message.

返回

Message

一个 Message,它引用队列中的一条消息。A Message that references a message in the queue.

例外

cursor 参数为 nullThe cursor parameter is null.

timeout 参数指定的值无效。The value specified for the timeout parameter is not valid. timeout 可能小于 Zero 或大于 InfiniteTimeoutPossibly timeout is less than Zero or greater than InfiniteTimeout.

transactionType 参数不是 MessageQueueTransactionType 成员之一。The transactionType parameter is not one of the MessageQueueTransactionType members.

在超时过期之前消息没有到达队列。A message did not arrive in the queue before the time-out expired.

- 或 --or-

访问“消息队列”方法时出错。An error occurred when accessing a Message Queuing method.

注解

使用此重载通过由参数定义的事务上下文从队列中接收消息 transactionType ,并在队列中没有消息时返回指定时间段。Use this overload to receive a message from a queue using a transaction context defined by the transactionType parameter, and return in a specified period of time if there are no messages in the queue.

Automatic transactionType 如果已存在附加到要用于接收消息的线程的外部事务上下文,请为参数指定。Specify Automatic for the transactionType parameter if there is already an external transaction context attached to the thread that you want to use to receive the message. 指定 Single 是否要以单个内部事务的形式接收消息。Specify Single if you want to receive the message as a single internal transaction. 您可以指定 None 是否要在事务上下文之外接收来自事务性队列的消息。You can specify None if you want to receive a message from a transactional queue outside of a transaction context.

Receive方法允许同步读取消息,从而将其从队列中删除。The Receive method allows for the synchronous reading of a message, thereby removing it from the queue. 后续调用 Receive 会返回队列中后面的消息。Subsequent calls to Receive return the messages that follow in the queue.

如果调用此方法来接收来自事务性队列的消息,则在事务中止的情况下,接收到的消息将返回到队列。If this method is called to receive a message from a transactional queue, the message that is received is returned to the queue if the transaction is aborted. 在提交事务之前,不会从队列中永久删除该消息。The message is not permanently removed from the queue until the transaction is committed.

若要在队列中读取消息而不将其从队列中删除,请使用 Peek 方法。To read a message in a queue without removing it from the queue, use the Peek method. 没有与调用返回的消息相关联的事务上下文 PeekThere is no transaction context associated with a message returned by a call to Peek. 由于不 Peek 会删除队列中的任何消息,因此没有任何内容可以通过调用回滚 AbortBecause Peek does not remove any messages in the queue, there is nothing to roll back by a call to Abort.

Receive如果当前线程在等待消息到达队列时可以被阻塞,则使用对的调用。Use a call to Receive when it is acceptable for the current thread to be blocked while it waits for a message to arrive in the queue. 线程在给定的时间段内被阻止,或在指定了参数的值的情况下无限期阻止 InfiniteTimeout timeoutThe thread is blocked for the given period of time, or indefinitely if you specified the value InfiniteTimeout for the timeout parameter. 如果应用程序处理应在不等待消息的情况下继续运行,请考虑使用异步方法 BeginReceiveIf the application processing should continue without waiting for a message, consider using the asynchronous method, BeginReceive.

下表显示了此方法是否在各种工作组模式下可用。The following table shows whether this method is available in various Workgroup modes.

工作组模式Workgroup mode 可用Available
本地计算机Local computer Yes
本地计算机和直接格式名称Local computer and direct format name Yes
远程计算机Remote computer No
远程计算机和直接格式名称Remote computer and direct format name Yes

另请参阅

适用于

线程安全性

方法不是线程安全的。The method is not thread safe.