MessageQueue.Receive MessageQueue.Receive MessageQueue.Receive MessageQueue.Receive Method

定義

接收佇列中的第一個訊息,並將它從佇列中移除。Receives the first message in the queue, removing it from the queue.

多載

Receive() Receive() Receive() 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) Receive(MessageQueueTransaction) Receive(MessageQueueTransaction) 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) Receive(MessageQueueTransactionType) Receive(MessageQueueTransactionType) 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) Receive(TimeSpan) Receive(TimeSpan) 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) Receive(TimeSpan, Cursor) 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) Receive(TimeSpan, MessageQueueTransaction) Receive(TimeSpan, MessageQueueTransaction) 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) Receive(TimeSpan, MessageQueueTransactionType) Receive(TimeSpan, MessageQueueTransactionType) 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) Receive(TimeSpan, Cursor, MessageQueueTransaction) 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) Receive(TimeSpan, Cursor, MessageQueueTransactionType) 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() Receive() Receive() 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,參考佇列中的第一個可用訊息。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 'Order


   
    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 'MyNewQueue

備註

使用此多載從佇列接收訊息, 或等到佇列中有訊息為止。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. 如果應用程式處理應該在不等待訊息的情況下繼續進行, 請考慮使用BeginReceive非同步方法。If 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) Receive(MessageQueueTransaction) Receive(MessageQueueTransaction) 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,參考佇列中的第一個可用訊息。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 'MyNewQueue

備註

使用此多載, 從交易式佇列接收訊息, 其使用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. 沒有與的呼叫Peek所傳回的訊息相關聯的交易內容。There is no transaction context associated with a message returned by a call to Peek. 因為Peek不會移除佇列中的任何訊息, 所以不會透過Abort呼叫來復原任何內容。Because 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. 如果應用程式處理應該在不等待訊息的情況下繼續進行, 請考慮使用BeginReceive非同步方法。If 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) Receive(MessageQueueTransactionType) Receive(MessageQueueTransactionType) 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 MessageQueueTransactionType MessageQueueTransactionType

其中一個 MessageQueueTransactionType 值,描述要與訊息相關聯的異動內容的類型。One of the MessageQueueTransactionType values, describing the type of transaction context to associate with the 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. 沒有與的呼叫Peek所傳回的訊息相關聯的交易內容。There is no transaction context associated with a message returned by a call to Peek. 因為Peek不會移除佇列中的任何訊息, 所以不會透過Abort呼叫來復原任何內容。Because 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. 如果應用程式處理應該在不等待訊息的情況下繼續進行, 請考慮使用BeginReceive非同步方法。If 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) Receive(TimeSpan) Receive(TimeSpan) 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 TimeSpan TimeSpan

TimeSpan,指出等待新訊息可以進行檢查的時間。A TimeSpan that indicates the time to wait until a new message is available for inspection.

傳回

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. 此範例會在等候訊息抵達佇列時, 暫停執行長達五秒。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 'Order


   
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 'MyNewQueue

備註

使用這個多載來接收訊息,如果佇列中沒有訊息,則在指定時間期限傳回。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 timeout參數的值, 則會無限期地封鎖。The thread will be blocked for the given period of time, or indefinitely if you specified the value InfiniteTimeout for the timeout parameter. 如果應用程式處理應該在不等待訊息的情況下繼續進行, 請考慮使用BeginReceive非同步方法。If 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) Receive(TimeSpan, Cursor) 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

參數

timeout
TimeSpan TimeSpan TimeSpan TimeSpan

TimeSpan,指出等待新訊息可以進行檢查的時間。A TimeSpan that indicates the time to wait until a new message is available for inspection.

cursor
Cursor Cursor Cursor Cursor

Cursor,保留訊息佇列中的特定位置。A Cursor that maintains a specific position in the message queue.

傳回

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) Receive(TimeSpan, MessageQueueTransaction) Receive(TimeSpan, MessageQueueTransaction) 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 TimeSpan TimeSpan

TimeSpan,指出等待新訊息可以進行檢查的時間。A TimeSpan that indicates the time to wait until a new message is available for inspection.

傳回

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 'MyNewQueue
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. 沒有與的呼叫Peek所傳回的訊息相關聯的交易內容。There is no transaction context associated with a message returned by a call to Peek. 因為Peek不會移除佇列中的任何訊息, 所以不會透過Abort呼叫來復原任何內容。Because 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 timeout參數的值, 則會無限期地封鎖。The thread will be blocked for the given period of time, or indefinitely if you specified the value InfiniteTimeout for the timeout parameter. 如果應用程式處理應該在不等待訊息的情況下繼續進行, 請考慮使用BeginReceive非同步方法。If 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) Receive(TimeSpan, MessageQueueTransactionType) Receive(TimeSpan, MessageQueueTransactionType) 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 TimeSpan TimeSpan

TimeSpan,指出等待新訊息可以進行檢查的時間。A TimeSpan that indicates the time to wait until a new message is available for inspection.

transactionType
MessageQueueTransactionType MessageQueueTransactionType MessageQueueTransactionType MessageQueueTransactionType

其中一個 MessageQueueTransactionType 值,描述要與訊息相關聯的異動內容的類型。One of the MessageQueueTransactionType values, describing the type of transaction context to associate with the 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. 沒有與的呼叫Peek所傳回的訊息相關聯的交易內容。There is no transaction context associated with a message returned by a call to Peek. 因為Peek不會移除佇列中的任何訊息, 所以不會透過Abort呼叫來復原任何內容。Because 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 timeout參數的值, 則會無限期地封鎖。The thread will be blocked for the given period of time, or indefinitely if you specified the value InfiniteTimeout for the timeout parameter. 如果應用程式處理應該在不等待訊息的情況下繼續進行, 請考慮使用BeginReceive非同步方法。If 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) Receive(TimeSpan, Cursor, MessageQueueTransaction) 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

參數

timeout
TimeSpan TimeSpan TimeSpan TimeSpan

TimeSpan,指出等待新訊息可以進行檢查的時間。A TimeSpan that indicates the time to wait until a new message is available for inspection.

cursor
Cursor Cursor Cursor Cursor

Cursor,保留訊息佇列中的特定位置。A Cursor that maintains a specific position in the message queue.

傳回

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. 沒有與的呼叫Peek所傳回的訊息相關聯的交易內容。There is no transaction context associated with a message returned by a call to Peek. 因為Peek不會移除佇列中的任何訊息, 所以沒有任何可透過Abort呼叫來復原的內容。Because 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 timeout參數的值, 則會無限期地封鎖。The thread is blocked for the given period of time, or indefinitely if you specified the value InfiniteTimeout for the timeout parameter. 如果應用程式處理應該在不等待訊息的情況下繼續進行, 請考慮使用BeginReceive非同步方法。If 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) Receive(TimeSpan, Cursor, MessageQueueTransactionType) 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

參數

timeout
TimeSpan TimeSpan TimeSpan TimeSpan

TimeSpan,指出等待新訊息可以進行檢查的時間。A TimeSpan that indicates the time to wait until a new message is available for inspection.

cursor
Cursor Cursor Cursor Cursor

Cursor,保留訊息佇列中的特定位置。A Cursor that maintains a specific position in the message queue.

transactionType
MessageQueueTransactionType MessageQueueTransactionType MessageQueueTransactionType MessageQueueTransactionType

其中一個 MessageQueueTransactionType 值,描述要與訊息產生關聯的交易內容類型。One of the MessageQueueTransactionType values that describes the type of transaction context to associate with the 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. 沒有與的呼叫Peek所傳回的訊息相關聯的交易內容。There is no transaction context associated with a message returned by a call to Peek. 因為Peek不會移除佇列中的任何訊息, 所以沒有任何可透過Abort呼叫來復原的內容。Because 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 timeout參數的值, 則會無限期地封鎖。The thread is blocked for the given period of time, or indefinitely if you specified the value InfiniteTimeout for the timeout parameter. 如果應用程式處理應該在不等待訊息的情況下繼續進行, 請考慮使用BeginReceive非同步方法。If 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
另請參閱

適用於